I have an array of objects (main array) and a filtered list. They have a selected property which has a value of true. I need to compare both of them and update the selected property to false if it is not present in the other array.
This is my implementation.
const data = [{
color: "red",
value: "#f00",
selected: true
},
{
color: "green",
value: "#0f0",
selected: true
},
{
color: "blue",
value: "#00f",
selected: true
},
{
color: "cyan",
value: "#0ff",
selected: true
},
{
color: "magenta",
value: "#f0f",
selected: true
},
{
color: "yellow",
value: "#ff0",
selected: true
},
{
color: "black",
value: "#000",
selected: true
}
]
const filtered = [{
color: "magenta",
value: "#f0f",
selected: true
}, {
color: "green",
value: "#0f0",
selected: true
}, {
color: "black",
value: "#000",
selected: true
}]
data.forEach(item => {
for(var key in filtered) {
if(filtered[key]['value'] === item.value) {
item.selected = false
}
}
})
console.log(data)
The expected output should be opposite of that.
[
{
"color": "red",
"value": "#f00",
"selected": false
},
{
"color": "green",
"value": "#0f0",
"selected": true
},
{
"color": "blue",
"value": "#00f",
"selected": false
},
{
"color": "cyan",
"value": "#0ff",
"selected": false
},
{
"color": "magenta",
"value": "#f0f",
"selected": true
},
{
"color": "yellow",
"value": "#ff0",
"selected": false
},
{
"color": "black",
"value": "#000",
"selected": true
}
]
Please advice. Is there a more better to achieve this?
P.S: I can use lodash as well.
Thanks.
value, or based on a combination ofcolorandvalue?