0

Guys what is the best approach to modified array of object with value from object. E.g: lets say that we have array and object like this:

let arr = [
{
        parameter: 'aaa', 
        isSomething: false
},
{
        parameter: 'bbb', 
        isSomething: false
}, 
{
        parameter: 'ccc', 
        isSomething: false
}
];

let obj = {aaa: false, bbb: true, ccc: true}

and output that I want to achieve is:

let arr = [
{
        parameter: 'aaa', 
        isSomething: false
},
{
        parameter: 'bbb', 
        isSomething: true
}, 
{
        parameter: 'ccc', 
        isSomething: true
}
];

Could you help me with this one? I would be grateful. Thanks

2
  • What exactly is the purpose of the first array? It seems like you just want to create an array based on the entries of obj - I don't understand what you need the first array for Commented May 18, 2022 at 10:14
  • 3
    Have you tried using a simple for loop? Something like arr.forEach(item => item.isSomething = obj[item.parameter]) should work Commented May 18, 2022 at 10:14

1 Answer 1

2

You can use Arra#map() combined with Destructuring assignment

Code:

const arr = [{parameter: 'aaa',isSomething: false},{parameter: 'bbb',isSomething: false},{parameter: 'ccc',isSomething: false}]

const obj = {
  aaa: false,
  bbb: true,
  ccc: true
}

const result = arr.map(({ parameter, isSomething }) => ({ 
  parameter, 
  isSomething: obj[parameter]
}))

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.