这是我的示例数组,其中包含id和项目以及项目注释说明。
let sampleArr = [
{
id:1,
item:"item",
notes:["one"]
},
{
id:2,
item:"item2",
notes:["one","two"]
},
{
id:3,
item:"item3",
notes:["one","two"]
}
]
在这里,我想将注释添加到带有以下注释的id:3中:“三”,所以我希望最终输出应该像在示例数组中一样。
{
id:3,
item:"item3",
notes:["one","two","three"]
}
答案 0 :(得分:2)
您可以创建一个基于id搜索元素并更新值的函数
let sampleArr = [{id: 1,item: "item",notes: ["one"]},{id: 2,item: "item2",notes: ["one", "two"]},{id: 3,item: "item3",notes: ["one", "two"]}]
const updateNotes = (id,value) =>{
return sampleArr.map(v=> {
return v.id == id ? {...v, notes: [...v.notes, value]} : v
})
}
console.log(updateNotes(3,'three'))
答案 1 :(得分:2)
这里的要旨是,[
{
"info" : [
{
"attribute":"Grade:",
"value":"Premium OR-Grade"
},
{
"attribute":"Disposable or Reusable:",
"value":"Reusable"
},
{
"attribute":"Handle:",
"value":"Finger Rings"
},
],
"name":"Product 1",
"sku":"4242"
}
]
时仅concat
个新的note
,否则只需返回旧项目
item.id === id
const addNoteById = (note, id) =>{
return sampleArr.map(item =>({
...item,
notes : item.id === id ? item.notes.concat(note) : item.notes
}))
}