'Modified array of object with value from a given object TS/JS

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



Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yosvel Quintero Arguelles