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 },
]
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 },
]
Share
Improve this question
edited Dec 27, 2020 at 14:09
ayaz
228 bronze badges
asked Dec 27, 2020 at 12:34
Alex BranAlex Bran
4631 gold badge8 silver badges20 bronze badges
3 Answers
Reset to default 6You 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)