Skip to content Skip to sidebar Skip to footer

Find Object By Property In An Array Of JavaScript Objects Inside Another Array

I have an array called mainarray which has three objects inside it. Inside each object there's another array called innerarray which has its own three objects. How do I get the fi

Solution 1:

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

or, if you use underscore and es5 only

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

Solution 2:

You can try the following code. It will bring you every second (in the sense of 2nd, 4th, 6th... etc) object in each subarray if they exist. If you are interested in only the second object then it's a matter of replacing the whole e.innerarray.reduce(... part with e.innerarray[2]. This will get you the whole desired 2nd object and then you can access any property of it that you like.

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);

Post a Comment for "Find Object By Property In An Array Of JavaScript Objects Inside Another Array"