Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript:向数组中的对象添加新属性_Javascript_Arrays - Fatal编程技术网

JavaScript:向数组中的对象添加新属性

JavaScript:向数组中的对象添加新属性,javascript,arrays,Javascript,Arrays,我正在尝试将一个项添加到数组中的现有对象中索引每个数组: const dataInput = [ { title: 'first', description: 'test 1' }, { title: 'second', description: 'test 1' }, ] 这就是我尝试过的: dataInput.map((data, index) => { availableItems.push({'idx':index}) }) 这将推送一个新对象,而不是将元素添加到现

我正在尝试将一个项添加到数组中的现有对象中索引每个数组:

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]
这就是我尝试过的:

dataInput.map((data, index) => {
  availableItems.push({'idx':index})
})
这将推送一个新对象,而不是将元素添加到现有的第一个和第二个对象

[
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
  {idx:0},
  {idx:1}
]
我怎样才能做到这一点?下面是我需要的

[
  { title: 'first', description: 'test 1', idx: 0 },
  { title: 'second', description: 'test 1', idx:1 },
]

您需要在每次迭代时添加一个新属性:

常量数据输入=[ {title:'first',description:'test 1'}, {title:'second',description:'test 1'}, ]; const res=dataInput.map data,index=>{…data,idx:index};
console.logres 您需要在每次迭代时添加一个新属性:

常量数据输入=[ {title:'first',description:'test 1'}, {title:'second',description:'test 1'}, ]; const res=dataInput.map data,index=>{…data,idx:index}; console.logres 另一种选择:

dataInput.forEach((element, index) => (element["idx"] = index));
另一种选择:

dataInput.forEach((element, index) => (element["idx"] = index));
另一种选择:

dataInput.forEach((element, index) => (element["idx"] = index));
常量数据输入=[ {title:'first',description:'test 1'}, {title:'second',description:'test 1'}, ] const result=dataInput.reduceac,cur,index=>{ acc.push{…cur,idx:index} 返回acc },[] console.logresult另一个选项:

dataInput.forEach((element, index) => (element["idx"] = index));
常量数据输入=[ {title:'first',description:'test 1'}, {title:'second',description:'test 1'}, ] const result=dataInput.reduceac,cur,index=>{ acc.push{…cur,idx:index} 返回acc },[] console.logresult