Вопрос

I need to create a function that takes in an array of Objects and returns the objects that match a specific set of criteria. What I have so far is fairly simple: (pseudocode)

// input:  conditions: { prop1: "x", prop2: "z"}
//         source: [{ prop1: "x", prop2: "y"}, { prop1: "x", prop2: "z"}];
// output: array of objects with the same properties & values
// ex:
// getObjects({ prop1: "x", prop2: "z"}, [{ prop1: "x", prop2: "y"}, { prop1: "x", prop2: "z"}]);
// returns: [{ prop1: "x", prop2: "z"}]

//....
var results = [];
for (var prop in obj) {
    var match = false;
    for (var cond in conditions) {
        if (cond === prop && conditions[cond] == obj[prop]) {
            match = true;
        }
    }
    if (match) {
        results.push(row);
    }
}
return results;

where conditions is an object that represents one or more properties that the matching object must possess.

The problem is that this is somehow returning duplicate objects, which obviously can't happen. I know there is a standard way to accomplish this (probably a programming 101 kind of thing), but my Google-foo is failing me.

NOTE: I can't use Array.prototype.filter here because of the context. I'm running through a set or rows in a table and only want to return the ones that match certain criteria.

Basically the idea is "return the objects that are similar to the input object.

Это было полезно?

Решение

You were very close from the solution.
If several properties match, you will add the 'row' for each match.
Just add it once per row, after loop on condition and loop on prop ended.
It is a matter of curly brace position :

var results = [];
for (var i =0; i<source.length; i++) {
    var row = source[i];
    var match = true;  
    var samePropCount = 0;
    for (var prop in row) {
        for (var cond in conditions) {
            if (cond === prop ) {
                samePropCount++;
                if (conditions[cond] != row[prop]) {
                   match = false;
                }
            }
        }  
    } 
    if (!samePropCount) match=false;
    if (match) {
        results.push(row);
    }
}
return results;

Другие советы

With underscore:

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

do you want to implement the function?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top