Skip to content
Advertisement

Find/Replace object in an array and add a key Javascript

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

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 tried this which is working but i don’t think so its a best 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;
            });
        }

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:

var bindingData = data.reduce((acc,datum)=>{
    if(selectedFilterList.some((item,index)=>(item.value === datum.value))){
     return acc.concat({...datum,isActive:true});   
}

return acc.concat({...datum,isActive:false});

},[]);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement