简体   繁体   English

如何使用react array map方法将项目添加到特定ID

[英]How to add items into specific Id using the react array map method

Here is my sample array which contains the id and item and item notes description. 这是我的示例数组,其中包含ID,项目和项目注释说明。

let sampleArr = [
   {
     id:1,
     item:"item",
     notes:["one"]
   },
   {
     id:2,
     item:"item2",
     notes:["one","two"]
   },
   {
     id:3,
     item:"item3",
     notes:["one","two"]
   }
]

Here I want to add the notes into id:3 with the notes:"three" so I am expecting my final output should be like into the sample array. 在这里,我想将注释添加到带有以下注释的id:3中:“三”,因此我希望最终输出应类似于示例数组。

{    
    id:3,
    item:"item3",
    notes:["one","two","three"]
 }

You can create a function which search element based on id and update value 您可以创建一个函数,该函数根据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')) 

The gist here is to only concat the new note when item.id === id otherwise just return the old item 这里的要点是只concatnoteitem.id === id否则只返回旧项目

const addNoteById = (note, id) =>{
    return sampleArr.map(item =>({
        ...item,
        notes : item.id === id ? item.notes.concat(note) : item.notes
    }))
} 

 const sampleArr = [{id:1,item:"item", notes:["one"]},{id:2,item:"item2",notes:["one","two"]},{id:3,item:"item3",notes:["one","two"]}] const addNoteById = (note, id) =>{ return sampleArr.map(item =>({ ...item, notes : item.id === id ? item.notes.concat(note) : item.notes })) } const result = addNoteById('foo', 3) console.log(result) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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