1

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 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

Another option:

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

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.