I try to use forEach
and push
a new array to achieve it, but the result is wrong.
const dummyArray = [
[45292, 1, 2],
[46292, 5, 6],
[47292, 9, 10],
]
const resultArray: any[] = []
dummyArray.forEach((elementValue, index) => {
resultArray.push({ date: '', price: '', code: '' })
elementValue.forEach(value => {
if (index === 0) {
resultArray[index] = { ...resultArray[index], date: value }
}
if (index === 1) {
resultArray[index] = { ...resultArray[index], price: value }
}
if (index === 2) {
resultArray[index] = { ...resultArray[index], code: value }
}
})
})
console.log('resultArray', resultArray)
the result becomes
[
{ date: 2, price: '', code: ''},
{ date: '', price: 6, code: ''},
{ date: '', price: '', code: 10},
]
I want it becomes like
[
{ date: 45292, price: 1, code: 2},
{ date: 46292, price: 5, code: 6},
{ date: 47292, price: 9, code: 10},
]
How do I achieve it ?
3
Answers
You need a different index for your if condition (subIndex):
You could also do below.
Or:
Note that, using reduce should come with a return inside reduce.
By far the simplest way to do this is with this one-liner – just map the dummyArray items to an object
It also uses modern patterns like destructuring and object shorthand