如何将数据推送到nodejs中对象数组的现有元素中?

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

我有这个对象数组列表。

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
}];

现在我想通过 forLoop 在此数组的特定元素中再推送两个数据:

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

我正在通过 cookie 将列表数据检索到其中一个路由中。

下面是我尝试根据匹配条件推送元素的代码。

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]);
      }
});

也许这不是正确的方法。请帮忙! 祝您排灯节快乐、繁荣。 干杯!

这里lists是一个对象数组。 所以 lists[item] 是一个对象,所以你不能把一个对象推到一个对象上。

在您的代码中 timeAndOTPArray 是一个对象。

在您的 lists 对象中,初始化一个名为 timeAndOTPArray

的空数组
var index = lists.findIndex(function(item){ return item.ID == req.params.ID});
lists[index].timeAndOTPArray.push(timeAndOTPArray);

我想这会有所帮助

var lists = req.cookies.list;

Object.keys(lists).forEach(function(item) {
    if(req.params.ID == lists[item].ID){  //look for match with ID
      Object.keys(timeAndOTPArray).forEach(key=>{
        lists[item][key]=timeAndOTPArray[key];
      })
      }
});

您可以使用 findIndex 和追加将对象更新到列表中,如下所示:

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

晚上好)我可以建议你最好的选择是用地图更新

const listItems = [
  {
    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,
  },
];

const paramId = 4;

const result = listItems.map((item) => {
  if (paramId === item.ID) {
    return {
      ...item,
      time: new Date(),
      OTP: 'smth',
    };
  }

  return item;
});

console.log('result', result);

对于附加,你可以这样做,

 lists[index] = Object.assign(lists[index], timeAndOTPArray);

如果你使用的是 es6,

lists[index] = {...lists[index], timeAndOTPArray};