I am attempting to modify an array of objects and I use a map inside a for loop. My implementation always seem to return the last item in the map.
Code:
let testArray = [
{
body: 'test sentence',
uid: "a"
},
{
body: 'Another test sentence',
uid: "b"
}
]
var allItems = []
for (var item of testArray) {
let splittedBody = item.body.split(' ')
let splittedArray = splittedBody.map((word, i) => {
item.body = word
item.objectID = `${item.uid}:${i}`
return item
})
allItems.push(splittedArray)
}
allItems = Array.prototype.concat(...allItems)
console.log(allItems)
The above code prints the following:
[ { body: 'sentence', uid: 'a', objectID: 'a:1' },
{ body: 'sentence', uid: 'a', objectID: 'a:1' },
{ body: 'sentence', uid: 'b', objectID: 'b:2' },
{ body: 'sentence', uid: 'b', objectID: 'b:2' },
{ body: 'sentence', uid: 'b', objectID: 'b:2' } ]
What I want is:
[ { body: 'test', uid: 'a', objectID: 'a:0' },
{ body: 'sentence', uid: 'a', objectID: 'a:1' },
{ body: 'Another', uid: 'b', objectID: 'b:0' },
{ body: 'test', uid: 'b', objectID: 'b:1' },
{ body: 'sentence', uid: 'b', objectID: 'b:2' } ]
EDIT:
Ideally, I would not like to construct another item in my map function because each object in the testArray
may have attributes that do not exist in other object. Constructing another item in the map function would mean that I have to check for undefined
in those attributes and this is very prone to errors.