在另一个数组中的JavaScript对象数组中按属性查找对象

时间:2016-06-10 14:05:23

标签: javascript jquery arrays object

我有一个名为mainarray的数组,里面有三个对象。在每个对象内部有另一个名为innerarray的数组,它有三个对象。

如何在每个innerarray内获取每个第二个对象的第一个属性?这可能吗?

mainarray: [{
    innerarray: [{
        property1: value1,
        property2: value2,
        property3: value3,
    }, {
        propertyiwant: value1,
        property2: value2,
        property3: value3,
    }, {
        property1: value1,
        property2: value2,
        property3: value3,
    }]
}, {
    innerarray: [{
        property1: value1,
        property2: value2,
        property3: value3,
    }, {
        propertyiwant: value1,
        property2: value2,
        property3: value3,
    }, {
        property1: value1,
        property2: value2,
        property3: value3,
    }]
}, { 
    innerarray: [{
        property1: value1,
        property2: value2,
        property3: value3,
    }, {
        propertyiwant: value1,
        property2: value2,
        property3: value3,
    }, {
        property1: value1,
        property2: value2,
        property3: value3,
    }]
}]

这个问题与From an array of objects, extract value of a property as array完全不同。在这里,我试图获取一个对象的属性,该对象位于另一个数组内的数组中。

2 个答案:

答案 0 :(得分:2)

mainarray.map(item => item.innerarray[1].propertyiwant);

或者,如果你只使用下划线和es5

_.map(mainarray, function(item){
    return item.innerarray[1].propertyiwant
});

答案 1 :(得分:2)

您可以尝试以下代码。如果它们存在,它将为每个子阵列中的每秒(在第2,第4,第6 ......等意义上)提供对象。如果您只对第二个对象感兴趣,则需要更换整个e.innerarray.reduce(..。部分e.innerarray[2]。这将为您提供所需的第二个对象,然后您可以访问它喜欢的任何属性。

var mainarray = [{
    innerarray: [{
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        propertyiwant: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }]
}, {
    innerarray: [{
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        propertyiwant: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }]
}, { 
    innerarray: [{
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        propertyiwant: "value1",
        property2: "value2",
        property3: "value3",
    }, {
        property1: "value1",
        property2: "value2",
        property3: "value3",
    }]
}],
mapped = mainarray.map(e => e.innerarray.reduce((p,c,i) => (i%2 && p.push(c),p),[]));
console.log(mapped);