Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Traversing Arrays by forEach

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading