繁体   English   中英

如何将元素添加到数组 javascript 中的 object

[英]how to add element to object in array javascript

我有一个对象数组,它的结构如下:

let array1 = [{}]
array1.push({
   title: 'myTitle1',
   extendedProps: {
      field1: 'hello'
   }
})

现在我正在尝试的是执行axios.get请求并使用返回的数据将新元素添加到array1中。 我成功地从 axios 请求中检索数据,但是,当我尝试推送数据时: res.data[i]._doc.userIsReg ,如下所示:

array1.push({
  ...array1,
  extendedProps: {
        ...array1.extendedProps,
        userIsReg: true
  }  
})

如您所见,我正在使用spread功能将array1中的当前数据包含到数组中,然后我尝试将 append 一个新元素userIsReg到 object extendedProps 现在,我假设这会起作用,但是,当我这样做时,它会在数组中创建新的 object 条目,并包括当前数组内部的所有内容(来自扩展功能),并在其中添加带有userIsReg的新条目。

所以为了更清楚,我从这个开始:

[{
   title: 'myTitle1',
   extendedProps: {
      field1: 'hello'
   }
},
{
   title: 'myTitle2',
   extendedProps: {
      field1: 'hello2'
   }
}, 
]

然后一旦我使用传播功能执行array1.push ,我得到这个:

 [{
       title: 'myTitle1',
       extendedProps: {
          field1: 'hello'
       }
    },
    {
       title: 'myTitle2',
       extendedProps: {
          field1: 'hello2'
       }
    }, 
    {
       title: 'myTitle1',
       extendedProps: {
          field1: 'hello',
          userIsReg: true
       }
    },
    {
       title: 'myTitle2',
       extendedProps: {
          field1: 'hello2',
          userIsReg: true
       }
    }, 
    ]

所以基本上将所有内容加倍,而不是将其附加到当前数组。 我将如何解决这个问题?

收到回复后,您可以执行以下操作

array1.map(element => ({...element, userIsReg: true}))

它会将 userIsReg 标志添加到数组的每个 object 中。

现在,如您所愿,您可以在extendedProps中使用以下内容

array1.map(element => (
    {...element, 
    extendedProps: {
       ...element.extendedProps, 
       userIsReg: true 
    }}))

当您在 let 类型中定义数组时,您可以通过以下方式进行:

array1 = [...array1.filter(item=> item.title === selected_item.title ),{
  ...selected_item,userIsReg: true 
}]

我所做的就是删除前一个元素并添加一个具有新值的新元素,如果你想保留数组的顺序,你可以对它进行排序

试试这样

 let array1 = [{ title: 'myTitle1', extendedProps: { field1: 'hello' } }, { title: 'myTitle2', extendedProps: { field1: 'hello2' } }]; array1.forEach(obj => { obj.extendedProps['userIsReg'] = true // this value is coming from API }); console.log(array1);

暂无
暂无

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

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