[英]How to change the array based on index in nested object javascript
I have a nested array object , key value
array,我有一个嵌套阵列对象,密钥
value
阵列,
based on index, replace the value with content parameter基于索引,用内容参数替换值
How to change the array value based on the index value in javascript如何根据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.您可以将
object.assign
以数组和对象作为值的数组。
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.