Searching and updating an element within an array while also inserting a new key in JavaScript

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;
            });
        }

Answer β„–1

To determine the presence of each item in the data inside the selectedFilterList and add an 'isActive' flag value accordingly, you can utilize the Array.reduce() method. By using Array.some(), you can check if each data item is present. Below is a snippet of the code:

var bindData = data.reduce((accumulator, item) => {
    if(selectedFilterList.some((selectedItem) => (selectedItem.value === item.value))){
        return accumulator.concat({...item, isActive:true});   
    }

    return accumulator.concat({...item, isActive:false});
},[]);

Answer β„–2

To update the data array based on the selectedFilterList array, iterate through each item in the data array. Check if there is a match between the label of the item and any label in the selectedFilterList array. If a match is found, set the isActive property of the item to true or the same as the isActive property of the matched item in the selectedFilterList array. If no match is found, set the isActive property to false.

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}];

for (const item of data) {
  const found = this.selectedFilterList.find(val => val.label === item.label);
  if (found) {
    item.isActive = found.isActive;
  } else {
    item.isActive = false;
  }
}

console.log(this.data);
.as-console-wrapper {min-height: 100%!important; top: 0}

Answer β„–3

To generate the bindingData array, we can utilize this.data.map function. It checks if the label is present in the selectedFilterList and sets the isActive flag accordingly.

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},
    {label: "Volvo", value: "Volvo", isActive: false}
]

if (this.selectedFilterList && this.selectedFilterList.length) {
    this.bindingData = this.data.map(value => {
        const isActive = !!this.selectedFilterList.find(f => f.label === value.label)?.isActive;
        return { ...value, isActive };
    });
} else {
    this.bindingData = this.data.map(value => {
        var newKey = Object.assign({}, value);
        newKey.isActive = false;
        return newKey;
    });
}

console.log(this.bindingData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing arguments inside the source attribute of an image or link tag in Node.js and

As a beginner in NodeJS, I am facing an issue with passing arguments inside links and image sources. In my template.html file, I have included various scripts and elements to create a search form. The issue arises when I try to incorporate values from the ...

Cannot perform mapping within an asynchronous function

Within the following snippet of code, I am retrieving information from an external api. When converting the data to json format, my intention was to loop through it and generate a modified version. Interestingly, the console.log(jsonData) within the map f ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Adding a blank data-columns attribute using jQuery:

I am trying to add the data-columns attribute for salvattore.js, but I am facing an issue where I cannot simply add the attribute without providing a value. Currently, my code looks like this: $('#liste-vdl div.view-content').attr("data-columns" ...

Turn the Array by k Positions

How can we rotate an array k times given an array and a number k? Sample Input 1 //number of of testcases 5 2 //5(array size) 2(K value) 1 2 3 4 5 /array elements Sample output 4 5 1 2 3 Here is the code snippet: import java.util. ...

Trouble invoking npm package.json scripts

The package.json file in my projects directory contains the following scripts section: "scripts": { "seed": "node bin/seed", "test": "echo \"Error: no test specified\" && exit 1" }, Executing $ npm test results in the followin ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...

Having trouble getting the HTML input textbox onChange event to fire properly?

This is the code I have been working on: <script language="JavaScript"> function toggle() { if (this.value=='1') { document.getElementById('dbOn').style.visibility='visible'; } el ...

Dividing the sentences inputted into a text area into an array and determining which sentence has been altered upon keyup

One of my current tasks involves handling the content within a textarea element: <textarea id="text"> Hello! Who am I? This is the third sentence. This, is another sentence. </textarea> Given that a textarea can be focused, I am seeking a met ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

Utilizing ExtJS and its control feature

I am facing an issue with the following code block: run: function(e, row){ var me = this; var container = Ext.getCmp('centercontainer'); try { container.removeAll(); } catch(e) { } // The code snippet below is act ...

How to show or hide a textbox in JavaScript?

Within my user control, there is a panel with two controls: ddlType, a drop-down list, and txtOthers, a text box. Initially, txtOthers is set to be invisible. The goal is for txtOthers to become visible when the user selects an option in ddlType that corr ...

Is there a way I can replace this for loop with the array.some function?

I am looking to update the filterOutEmails function in the following class to use array.some instead of the current code. export class UsertableComponent { dataSource: MatTableDataSource<TrialUser> createTableFromServer = (data: TrialUsers[], ...

Mastering the art of utilizing particles.js

Particles.js doesn't seem to be functioning properly for meβ€”I'm struggling to pinpoint the issue. Any guidance or suggestions would be greatly welcomed, as I'm unsure whether it's related to an external dependency... HTML: <div ...

"Users have reported that the Express body-parser feature sometimes results in req.body returning

I have developed a basic Express server that utilizes the body-parser module to access POST parameters. Here is how my application is structured: /index.js: 'use strict'; const express = require('express'); const app = express(); con ...

Mapping Service by Google - Navigate from your current location to desired destination

I have a script that currently displays a route for either car or transit depending on the user's selection. I am looking to adapt this script to set the origin as the user's current location and route from there to a set latitudes and longitudes ...

determine the quantity and categorize them

I am currently utilizing python in conjunction with pymongo. Within a mongo collection, I am storing various messages from different countries. Each document contains a country short code to indicate its origin. How can I group these messages by country c ...

Integrating PHP code into a React.js application can provide

I am currently integrating react.js into a section of my app and exploring the possibility of embedding some PHP code into react.js. This would allow me to avoid having to completely rewrite the backend that was originally written in PHP. Here's an ex ...

"Troubleshooting the issue of nested jQuery Ajax requests failing to execute properly

UPDATE: I'm getting an error saying that my li tag is considered an illegal token. I'm unsure how to resolve this issue as I believed I was appending it within a ul tag I'm tasked with fetching a JSON array of public Github repositories and ...

Adding turbolinks to an HTML document can be achieved without the need for a

Recently delving into the world of turbolinks, I discovered that it can be employed independently without relying on a client-side javascript framework. Eager to test this out, I created a bootstrap 4 template and attempted to install it. Firstly, I downl ...