简体   繁体   中英

How to change the array based on index in nested object javascript

I have a nested array object , key value array,

based on index, replace the value with content parameter

How to change the array value based on the index value in javascript

function changeValue(i,content){
 var result = obj.map(e=>{
     ...e,
     value: value[content]
  })

}

var obj=[
  {id:0, value:["SG","10","img"]}
]

Expected Output:
this.changeValue(1,"40");
[
 {id:0, value:["SG","40","img"]}
]

this.changeValue(0,"TH")
[
 {id:0, value:["TH","10","img"]}
]

You can change the value by changing the index directly.

 var obj = [ { id: 0, value: ["SG","10","img"] } ]; function changeValue(i, content){ var result = obj.map(e => { const value = [...e.value]; value[i] = content; return { ...e, value }; }); return result; } console.log(changeValue(1,"40")); console.log(changeValue(0,"TH"));

You could take object.assign to an array with the array and an object as values.

 function changeValue(i, content) { return obj.map(e => ({ ...e, value: Object.assign([], e.value, { [i]: content }) })); } var obj = [{ id:0, value: ["SG", "10", "img"] }]; console.log(changeValue(1, "40")); // [{ id: 0, value: ["SG", "40", "img"] }] console.log(changeValue(0, "TH")); // [{ id: 0, value: ["TH", "10"," img"] }]
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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