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