Patterns for combining arrays and objects (associative arrays)

If you are a beginner, you may have trouble dealing with data structures that are a combination of arrays and objects. Here we will show you how to scan the elements of each combination.

TOC

Array

let array = [1, 2, 3]
array.forEach(elm => {
  console.log(elm)
})
1
2
3

Array – Array

let array = [[1, 2, 3], [1, 2, 3]]
array.forEach(elm => {
  elm.forEach(elm => {
    console.log(elm)
  })
})
1
2
3
1
2
3

Array – Object

let array = [
  {key1: 1, key2: 2, key3: 3},
  {key1: 1, key2: 2, key3: 3}
]
array.forEach(elm => {
  Object.keys(elm).forEach(key => {
    console.log(`key: ${key} value: ${elm[key]}`)
  })
})
key: key1 value: 1
key: key2 value: 2
key: key3 value: 3
key: key1 value: 1
key: key2 value: 2
key: key3 value: 3

Object

let object = {key1: 1, key2: 2, key3: 3}
  
Object.keys(object).forEach(key => {
  console.log(`key: ${key} value: ${object[key]}`)
})
key: key1 value: 1
key: key2 value: 2
key: key3 value: 3

Object – Array

let object = {
  key1: [1, 2, 3],
  key2: [4, 5, 6]
}

Object.keys(object).forEach(key => {
  object[key].forEach(elm => {
    console.log(elm)
  })
})
1
2
3
4
5
6

Object – Object

let object = {
  key1: {x: 1, y: 2},
  key2: {x: 3, y: 4}
}

Object.keys(object).forEach(keyX => {
  Object.keys(object[keyX]).forEach(keyY => {
    console.log(`keyX: ${keyX} keyY: ${keyY} value: ${object[keyX][keyY]}`)
  })
})
keyX: key1 keyY: x value: 1
keyX: key1 keyY: y value: 2
keyX: key2 keyY: x value: 3
keyX: key2 keyY: y value: 4
Let's share this post !
TOC