I am trying to add a key to an Object of Array as isActive: true,
and then I want to find the object in the actual array with the same label as that of selectedFilterList
and replace it in this.bindingData
else add isActive: false
JavaScript
x
28
28
1
if (this.selectedFilterList && this.selectedFilterList.length) {
2
//Do something
3
} else {
4
this.bindingData = this.data.map((value) => {
5
var newKey = Object.assign({}, value);
6
newKey.isActive = false;
7
return newKey;
8
});
9
}
10
11
this.data = [
12
{ label: "Audi", value: "Audi" },
13
{ label: "BMW", value: "BMW" },
14
{ label: "Fiat", value: "Fiat" },
15
{ label: "Honda", value: "Honda" },
16
{ label: "Jaguar", value: "Jaguar" },
17
{ label: "Mercedes", value: "Mercedes" },
18
{ label: "Renault", value: "Renault" },
19
{ label: "VW", value: "VW" },
20
{ label: "Volvo", value: "Volvo" },
21
];
22
23
this.selectedFilterList = [
24
{ label: "Audi", value: "Audi", isActive: true },
25
{ label: "Fiat", value: "Fiat", isActive: true },
26
{ label: "BMW", value: "BMW", isActive: true },
27
];
28
I have tried this which is working but i don’t think so its a best approach
JavaScript
1
21
21
1
if (this.selectedFilterList && this.selectedFilterList.length) {
2
this.bindingData = this.data.map(value => {
3
var newKey = Object.assign({}, value);
4
newKey.isActive = false;
5
return newKey;
6
});
7
this.bindingData.map(data => {
8
this.selectedFilterList.forEach(value => {
9
if (value.label == data.label) {
10
data.isActive = value.isActive;
11
}
12
});
13
});
14
} else {
15
this.bindingData = this.data.map(value => {
16
var newKey = Object.assign({}, value);
17
newKey.isActive = false;
18
return newKey;
19
});
20
}
21
Advertisement
Answer
You can use Array.prototype.reduce()
on data
, check if each item in data is present in selectedFilterList
using Array.prototype.some()
and add isActive
flag value accordingly. Here is the sample code:
JavaScript
1
9
1
var bindingData = data.reduce((acc,datum)=>{
2
if(selectedFilterList.some((item,index)=>(item.value === datum.value))){
3
return acc.concat({datum,isActive:true});
4
}
5
6
return acc.concat({datum,isActive:false});
7
8
},[]);
9