I am trying to update an array of objects. The active
key will be set to true based on user’s selection or the array of strings.
For an instance, on selecting ABC, DEF
, the active
key will be set to true
for these two Ids.
const defaultArray = [
{
"active": true,
"id": 1,
"name": "ABC",
"value": "1"
},
{
"active": true,
"id": 2,
"name": "DEF",
"value": "2"
},
{
"active": true,
"id": 3,
"name": "GHI",
"value": "3"
}
]
const selectedArray = [
"ABC",
"DEF"
]
So now I need to create a new Array based on the default array and assign active=true
only for array of string in selecetedArray
.
Result will look like
const newArray = [
{
"active": true,
"id": 1,
"name": "ABC",
"value": "1"
},
{
"active": true,
"id": 2,
"name": "DEF",
"value": "2"
},
{
"active": false,
"id": 3,
"name": "GHI",
"value": "3"
}
]
I tried.
const arrCopy = [...defaultArray]
arrCopy.forEach(x => x.active = false)
arrCopy.forEach(x => {
if(selectedArray.includes(x.name))
x.active = true
})
console.log(arrCopy)
The above code works, but is there any more standard way to achieve the same. thanks
>Solution :
You don’t need two loops to achieve that, you can directly use map
method on the defaultArray
.
defaultArray.map(x => ({...x, active: selectedArray.includes(x.name)}))
const defaultArray = [
{
"active": true,
"id": 1,
"name": "ABC",
"value": "1"
},
{
"active": true,
"id": 2,
"name": "DEF",
"value": "2"
},
{
"active": true,
"id": 3,
"name": "GHI",
"value": "3"
}
]
const selectedArray = [
"ABC",
"DEF"
]
const newArray = defaultArray.map(x => ({...x, active: selectedArray.includes(x.name)}))
console.log(newArray)