Reputation: 35
const inventory = [
{ name: { vegetable: 'carrot' }, quantity: 2 },
{ name: { meat: 'pork' }, quantity: 0 },
{ name: { fruit: 'cherries' }, quantity: 5 },
];
const result = inventory.find(name => name === { fruit: 'cherries' });
console.log(result);
I have an array of nested objects and I'm trying to find out if there is one including the { fruit: 'cherries' }
object but I get undefined as a result.
So I guess you can't pass an object as a search parameter?
Upvotes: 1
Views: 133
Reputation: 35
Thanks for all the suggestions. I think I found a solution to my problem.
I used array.map
to create a new array consisting of only the name objects.
Then I used JSON.stringify
on selectedOption
and on the elements in the new array to find a match and/or index.
There is probably a better way of doing it but this is working OK. Feel free to point out any potential flaws in my approach.
const selectedOption = {fruit_red: "cherries", fruit_green: "kiwi"}
const inventory = [
{ name: { vegetable: 'carrot' }, quantity: 2 },
{ name: { meat: 'pork' }, quantity: 0 },
{ name: { fruit_red: 'cherries', fruit_green: 'kiwi' }, quantity: 5 },
{ name: { fruit_red: 'cherries', fruit_green: 'apple' }, quantity: 3 },
];
const names = inventory.map(item => item.name)
const resultIndex = names.findIndex(name => JSON.stringify(name) === JSON.stringify(selectedOption));
console.log(resultIndex)
const result = names.find(name => JSON.stringify(name) === JSON.stringify(selectedOption));
console.log(result)
console.log(inventory[resultIndex])
Upvotes: 0
Reputation: 38199
You need to write full path to the object and access to object through .
sign:
const result = inventory.find(name => name.name.fruit === 'cherries');
An example:
const inventory = [
{ name: { vegetable: 'carrot' }, quantity: 2 },
{ name: { meat: 'pork' }, quantity: 0 },
{ name: { fruit: 'cherries' }, quantity: 5 },
];
const result = inventory.find(name => name.name.fruit === 'cherries');
console.log(result);
It will be better seen in debugger what there is actual path to your properties of object:
const result = inventory.find(name => {
if(name.name.fruit === 'cherries')
return name;
return;
});
console.log(result);
Upvotes: 1
Reputation: 1618
Please explore Sbtree module or TyrDb module (TyrDb is a wrapper on top of Sbtree with abstracted API). These libraries let you search nested element.
Upvotes: 1
Reputation: 48437
You can't compare objects because they have different references. One way could be using destructuring and just simply access the fruit
property in order to compare it with a given value.
const inventory = [
{ name: { vegetable: 'carrot' }, quantity: 2 },
{ name: { meat: 'pork' }, quantity: 0 },
{ name: { fruit: 'cherries' }, quantity: 5 },
];
const result = inventory.find(({name}) => name.fruit == "cherries");
console.log(result);
Upvotes: 0