Home > Mobile >  Traversing Arrays by forEach
Traversing Arrays by forEach

Time:01-15

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?

CodePudding user response:

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)

CodePudding user response:

You can use reduce method on an array to convert the array to a map. Or You can use Object.fromEntries if your env supports the latest version of ES2017.

filtered2 = [
  ["deviceName", "TestDevice00003"],
  ["hwModelName", "TestHwModel03"],
  ["deviceTypeName", "TestDeviceType03"],
  ["serviceTag", "A1A03"],
];
const toMap = (arr = []) =>
  arr.reduce((acc, [key, value]) => {
    acc[key] = value;
    return acc;
  }, {});

console.log(toMap(filtered2))

/// Other way
console.log(Object.fromEntries(filtered2))

  •  Tags:  
  • Related