0

Basically, here is what I am trying to do.

  1. Go through each entry of the 'food' array and check whether the 'category' value is included in the 'target' array.
  2. Insert another key/value pair (target:true or target:false) accordingly.

i.e.,

const food = [
   {category: 'fruit', price: 5}, 
   {category: 'meat', price: 10}, 
   {category: 'drink', price: 3}
];

const target = ['fruit', 'meat'];

const result = [
   {category: 'fruit', price: 5, target: true}, 
   {category: 'meat', price: 10, target: true}, 
   {category: 'drink', price: 3, target: false}
];

What will be the code to do this? Thanks a lot in advance!

1 Answer 1

1

Array.prototype.map()

Array.prototype.includes()

const food = [
    { category: "fruit", price: 5 },
    { category: "meat", price: 10 },
    { category: "drink", price: 3 },
];
const target = ["fruit", "meat"];

const result = food.map(f => ({ ...f, target: target.includes(f.category) }));

console.log(result);

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

Comments

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.