将数组的字符串元素与另一个数组的对象元素属性进行比较

时间:2012-03-17 02:18:23

标签: javascript arrays object

所以,标题大部分都是这样说的,我举一个例子:

var foo = ['one', 'two', 'three'];
var bar = [
        {   
            integer: 1,
            string: 'one'
        },
        {   
            integer: 3,
            string: 'three'
        }       
    ];

现在,我想知道如何针对数组foo中所有对象的每个string属性获取bar中每个元素的正匹配列表

4 个答案:

答案 0 :(得分:4)

首先,在foo中创建一组所有元素,以避免方形复杂性:

var fooSet = {};    
for(var i = 0; i < foo.length; i++) {
    var e = foo[i];
    fooSet[e] = true;
}

然后,浏览bar并收集匹配项:

var matches = [];
for(var i = 0; i < bar.length; i++) {
    var e = bar[i];
    if(fooSet[e.string]) {
           matches.push(e);
    }
}

在此之后,matches数组将包含bar中与foo元素匹配的元素。

这是一个实例:

答案 1 :(得分:0)

循环遍历其中一个数组,检查每个项目与另一个项目:

var matches = [],
    i, j;

for (i=0; i < bar.length; i++)
    if (-1 != (j = foo.indexOf(bar[i].string)))
       matches.push(foo[j]);

// matches is ['one', 'three']

显然,如果您希望matches包含bar而不是foo中的项目,只需将.push()语句更改为matches.push(bar[i]);

当然,上述假设您不关心是否支持在数组上没有.indexOf()的旧浏览器,或者您可以使用a shim

答案 2 :(得分:0)

此:

// foo & bar defined here

// put all the keys from the foo array to match on in a dictionary (object)
var matchSet = {};
for (var item in foo)
{
    var val = foo[item];
    matchSet[val] = 1;
}

// loop through the items in the bar array and see if the string prop is in the matchSet
// if so, add it to the matches array
var matches = [];
for (var i=0; i < bar.length; i++)
{
    var item = bar[i];
    if (matchSet.hasOwnProperty(item['string']))
    {
        matches.push(item['string']);
    }
}

// output the matches (using node to output to console)
for (var i in matches)
{
    console.log(matches[i]);
}

输出:

match: one
match: three

注意:使用节点以交互方式运行

答案 3 :(得分:0)

这两项工作。取决于您希望如何使用您可以修改的数据。

http://jsfiddle.net/KxgQW/5/

WAY ONE

//wasn't sure which one you want to utilize so I'm doing both
//storing the index of foo to refer to the array
var wayOneArrayFOO= Array();
//storing the index of bar to refer to the array
var wayOneArrayBAR= Array();

var fooLength = foo.length;
var barLength = bar.length;


/*THE MAGIC*/                
//loop through foo
for(i=0;i<fooLength;i++){

    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayOneArrayFOO.push(i);
            wayOneArrayBAR.push(j);    
        }
    }

}

两个方式

//storing the value of foo
var wayTwoArrayFOO= Array();
//storing the value of bar
var wayTwoArrayBAR= Array();            


/*THE MAGIC*/      
//loop through foo
for(i=0;i<fooLength;i++){

    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayTwoArrayFOO.push(foo[i]);
            wayTwoArrayBAR.push(bar[j]);    
        }
    }

}