Search code examples
node.jsarraysjsonpusharrayobject

How to push data into existing element of the array of objects in nodejs?


I have this array list of objects.

var list = [{
  'ID':1,
  'name' : 'Vikas Yadav',
  'mobile':8095638475,
  'sent':false
},
{
'ID':2,
'name' : 'Rajat Shukla',
'mobile':7486903546,
'sent':false

},
{
'ID':3,
'name' : 'Munna Bhaiya',
'mobile':9056284550,
'sent':false
},
{
'ID':4,
'name' : 'Guddu Pandit',
'mobile':7780543209,
'sent':false
},
{
'ID':5,
'name' : 'Srivani Iyer',
'mobile':8880976501,
'sent':false
}];

Now I want to push two more datas in specific element of this array via forLoop as:

var timeAndOTPArray = {
  "time" : new Date(),
  "OTP": req.params.ran
}

I am retrieving the list data via cookies into one of the route.

Below is the code I am trying to push the element according to the matching condition.

var lists = req.cookies.list;

Object.keys(lists).forEach(function(item) {
    if(req.params.ID == lists[item].ID){  //look for match with name
      (lists[item]).push(timeAndOTPArray);
        newAddedList.push(lists[item]);
        console.log(item, lists[item]);
      }
});

Perhaps it's not the correct way. Please help! Wish you a happy and a prosperous Diwali. Cheers!


Solution

  • You can use findIndex and append to update the object into list like this:

    //List only with ID, easier to read the code
    var list = [{'ID':1,},{'ID':2,}]
    //your object
    var timeAndOTPArray = {
      "time" : new Date(),
      "OTP": "otp"
    }
    //Index where object with ID == 2 is
    var index = list.findIndex(obj => obj.ID == 2);
    //Append the 'timeAndOTPArray' properties into the object itself
    list[index] = {"time": timeAndOTPArray.time, "OTP":timeAndOTPArray.OTP, ...list[index]}
    
    console.log(list)