Reputation: 2685
I was trying to get the property value only using a map function. I know If I use map then its going to return an array of elements. So, here is what I am trying to do.
I have this array, of object
mainarray = [{ foo : '1' , id:'2' }, { foo : '2' , id:'3' },{ foo : '1' , id:'4' }];
Now, here what I am doing is (data is some different array).
let count;
if (data) {
if ((data[0].foo) && (data[0].foo)) {
count = this.state.mainarray.map((object, index) => {
if ((object.Id === data[0].id) && (data[0].foo === object.foo)) {
return object;
}
});
}
}
I have done like this. Now here, if it did not match anything then it returns an array with all undefined
values, as many elements are there in that.
[undefined,undefined]
But I actually tried with object.foo
, so it should return only that value, But it is not returning. So, I'am stuck over here. Can any one help me with this?
Upvotes: 1
Views: 2212
Reputation: 8060
I think you want to use filter
method
let count;
if (data) {
if ((data[0].foo) && (data[0].foo)) {
count = this.state.mainarray.filter((object) => (object.Id === data[0].id) && (data[0].foo === object.foo)).length;
}
}
Upvotes: 1
Reputation: 112827
You might want to use find
instead, and if a match was found you can use that object's foo
value.
Example
const mainarray = [
{ foo: "1", id: "2" },
{ foo: "2", id: "3" },
{ foo: "1", id: "4" }
];
const idToFind = "3";
const obj = mainarray.find(element => element.id === idToFind);
const count = (obj && obj.foo) || "0";
console.log(count);
Upvotes: 0