JavaScript: Add new attribute to object in an array

Viewed 1381

I am trying to add an item into an existing object in an array (index each array):

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]

This is what I've tried:

dataInput.map((data, index) => {
  availableItems.push({'idx':index})
})

This pushes a new object instead of adding the element to the existing first and second.

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

How could I achieve that? (below is what I need)

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

You need to add a new attribute at each iteration:

const dataInput = [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
];

const res = dataInput.map( (data, index) => ({...data, idx:index}) );

console.log(res);

Another option:

dataInput.forEach((element, index) => (element["idx"] = index));

Another option:

const dataInput= [
  { title: 'first', description: 'test 1' },
  { title: 'second', description: 'test 1' },
]

const result = dataInput.reduce((acc, cur, index) => {
    acc.push({...cur, idx: index})
    return acc
},[])

console.log(result)

Related