2

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"]
 }
1
  • Yes you are right, deleted my comment. Never mind Commented Aug 30, 2019 at 19:08

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I can not write this way like let returnData; returnData = sampleArr.map(item =>{ ...item, notes : item.id === id ? item.notes.concat(note) : item.notes })
@Pintu you need to wrap return value by (), i.e sampleArr.map(item => ({...
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.