1
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.

1
  • surely you've tried to write some code to accomplish this, can you add it to your post please so we can better help? Commented Mar 18, 2020 at 13:50

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

any idea/example how can I handle my idea of buylist? maybe I should use only arrays?
0

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

1 Comment

everything works fine, thank you so much for help & clean code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.