简体   繁体   English

搜索对象数组javascript

[英]Searching an object array javascript

I am trying to create a search function that will take an array of objects as the first argument and returns an array of all objects that have matching property/value pairs from the second argument. 我正在尝试创建一个搜索函数,该函数将对象数组作为第一个参数,并从第二个参数返回具有匹配的属性/值对的所有对象的数组。 Here is what I have so far: 这是我到目前为止的内容:

function where(collection, source) {

    var arr = [];
    var propName = Object.keys(source);     

    //console.log((collection[2][propName] == source[propName])? "true" : "false");

    var i = 0;
    var z = 0;
    var cl = collection.length;
    var pl = propName.length;

    for(z = 0; z < 1; z++){
        for(i= 0; i < cl; i++){             

            if(collection[i][propName[z]] == source[propName[z]]){

                //console.log(collection[i]);

                arr.push(collection[i]);

            }       

        }
    }

    console.log(arr);

}

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, 
       { first: "Tybalt", last: "Capulet" }], { last: "Capulet", first: "Mercutio" });

It works when I have only one key/value pair as the search parameter like so: 当我只有一个键/值对作为搜索参数时,它会起作用,如下所示:

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, 
       { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

but with two key/value pairs it only returns item that match to the first pair. 但具有两个键/值对,它仅返回与第一对匹配的项目。 Any help would be greatly appreciated. 任何帮助将不胜感激。 BTW I'm looking to do this with vanilla JS. 顺便说一句,我正在用香草JS做。 Thanks Very Much!!! 非常感谢!!!

for(z = 0; z < 1; z++){更改1pl中 ,就像for(z = 0; z < pl; z++){ ,否则您只是在z中循环了0值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM