Amit
Amit

Reputation: 353

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.

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,
    item:"item3",
    notes:["one","two","three"]
 }

Upvotes: 2

Views: 1721

Answers (2)

Dupocas
Dupocas

Reputation: 21347

The gist here is to only concat the new note when item.id === id otherwise just return the old item

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)

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You can create a function which search element based on id and update value

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'))

Upvotes: 2

Related Questions