Reputation: 13
const data = [
{ name: "Table", color: ["green", "red", "blue"], price: 300 },
{ name: "Desk", color: ["white", "yellow", "grey"], price: 300 },
{ name: "Desk", color: ["black", "pink", "green"], price: 500 },
];
Hello, I'm trying to code buy-list in objects, but I met logic problem here because for example, there can be same object (called Desk) but with different array (color) for different price.
How can I grab info about price if my script will meet 2 requirements - it will be Desk, color will be black for example, and result needs to be 500 using .find() function returns 1st object (in this case: { name: "Desk", color: ["white", "yellow", "grey"], price: 300 })
Please help :D Greetings.
Upvotes: 1
Views: 83
Reputation: 386654
You could take Array#find
with Array#includes
for the wanted color.
As result you get either an item or undefined
, if the request does not match.
const
data = [{ name: "Table", color: ["green", "red", "blue"], price: 300 }, { name: "Desk", color: ["white", "yellow", "grey"], price: 300 }, { name: "Desk", color: ["black", "pink", "green"], price: 500 }],
request = { name: 'Desk', color: 'black' },
result = data.find(({ name, color }) =>
name === request.name &&
color.includes(request.color)
);
console.log(result);
Upvotes: 0
Reputation: 958
Given just the information your data has you either need to come up with a cumbersome approach like trying to find the color as well, or make sure to include a unique identifier like a SKU into your objects.
Upvotes: 1