简体   繁体   中英

Add or replace object to array with dynamic key name in javascript (reactJS)

I have a number of select, when i onChange them i want to keep in componente state the selected value the onChange function i call do something like this:

function validateVariations(event) {
    console.log(event.target.value);
    console.log(event.target.name);

    setSelected((selected) => [
      ...selected,
      { [event.target.name]: event.target.value },
    ]);

    .... //OTHER PROCESS
 }

basically i add to state select an object like:

[{Weight: "250"},{Pack: "Tin"}]

but using it a couple of time it fill up with the history changes like this:

[{Weight: "250"},{Weight: "500"},{Weight: "250"},{Pack: "Tin"}, {Pack: "Card"}]

so i need to add the { [event.target.name]: event.target.value } only if its not present an object with key [event.target.name] , otherwise i need to replace it.

i tried using findIndex but im not able to reference to a dynamically named key

this is not working:

var i = data.findIndex(function(e) {
    return e.[event.target.name] == event.target.name;
});

any elegant solution?

Based on the format of your data, you could use this:

var i = data.findIndex(function(e) {
    return Object.keys(e)[0] === event.target.name;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM