My goal is to add a key to an Object of Array as isActive: true. I then need to locate the object in the actual array with the same label as that of selectedFilterList
and replace it in this.bindingData
, or add isActive: false
if it doesn't exist.
if (this.selectedFilterList && this.selectedFilterList.length) {
//Do something
} else {
this.bindingData = this.data.map((value) => {
var newKey = Object.assign({}, value);
newKey.isActive = false;
return newKey;
});
}
this.data = [
{ label: "Audi", value: "Audi" },
{ label: "BMW", value: "BMW" },
{ label: "Fiat", value: "Fiat" },
{ label: "Honda", value: "Honda" },
{ label: "Jaguar", value: "Jaguar" },
{ label: "Mercedes", value: "Mercedes" },
{ label: "Renault", value: "Renault" },
{ label: "VW", value: "VW" },
{ label: "Volvo", value: "Volvo" },
];
this.selectedFilterList = [
{ label: "Audi", value: "Audi", isActive: true },
{ label: "Fiat", value: "Fiat", isActive: true },
{ label: "BMW", value: "BMW", isActive: true },
];
I have implemented the following, and it is working but I believe there may be a better approach:
if (this.selectedFilterList && this.selectedFilterList.length) {
this.bindingData = this.data.map(value => {
var newKey = Object.assign({}, value);
newKey.isActive = false;
return newKey;
});
this.bindingData.map(data => {
this.selectedFilterList.forEach(value => {
if (value.label == data.label) {
data.isActive = value.isActive;
}
});
});
} else {
this.bindingData = this.data.map(value => {
var newKey = Object.assign({}, value);
newKey.isActive = false;
return newKey;
});
}