Trying to traverse an array into an object with key/pair (yes I know of reduce):
This is the array:
filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]
But for some reason when I do forEach:
filtered2.forEach( (indiv) => {
console.log([indiv[0]]+" | " +[indiv[1]])
obj3 = {
...obj3,
[[indiv[0]][0]] : [indiv[1]]
}
})
Console.log will see each (indiv) as "hwModelName | TestHwModel03"
at [indiv[0]]+" | " +[indiv[1]], so both are basic strings
But the forEach function sees [indiv[1]] as Array ["TestHwModel03"]
So I have to go one more depth level [indiv[1]][0] into the array to get the unwrapped string "TestHwModel03"
Why there this difference?
>Solution :
Remove the square brackets surrounding the value.
filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]
let obj3 = {}
filtered2.forEach( (indiv) => {
obj3 = {
...obj3,
[[indiv[0]][0]] : indiv[1]
}
})
console.log(obj3)
Although it’s much simpler to use Object.fromEntries:
filtered2 = [["deviceName", "TestDevice00003"], ["hwModelName", "TestHwModel03"], ["deviceTypeName", "TestDeviceType03"], ["serviceTag", "A1A03"]]
let obj3 = Object.fromEntries(filtered2)
console.log(obj3)