Friday, 14 May 2021

I was asked about extracting a subarray from an array of objects...

The function needed to be compliant with ES5, and the data was in this format:

const bob = [
  {
    "bob": {
      "1.1": 11,
      "1.2": [
        {
          "1.2.1": 121
        }, {
          "1.2.2": 122
        }
      ],
      "list": [
        {
          "bob.1.1": 121
        }, {
          "bob.1.2": 122
        }
      ]
    }
  }, {
    "bob": {
      "2.1": 11,
      "2.2": [
        {
          "2.2.1": 121
        }, {
          "2.2.2": 122
        }
      ],
      "list": [
        {
          "bob.2.1": 121
        }, {
          "bob.2.2": 122
        }
      ]
    }
  }, {
    "bob": {
      "3.1": 11,
      "3.2": [
        {
          "3.2.1": 121
        }, {
          "3.2.2": 122
        }
      ]
    }
  }, {
    "fred": {
      "4.1": 11,
      "4.2": [
        {
          "4.2.1": 121
        }, {
          "4.2.2": 122
        }
      ],
      "list": [
        {
          "bob.4.1": 121
        }, {
          "bob.4.2": 122
        }, {
          "bob.4.3": 122
        }
      ]
    }
  }, {
    "bob": {
      "5.1": 11,
      "5.2": [
        {
          "5.2.1": 121
        }, {
          "5.2.2": 122
        }
      ],
      "list": [
        {
          "bob.5.1": 121
        }, {
          "bob.5.2": 122
        }, {
          "bob.5.3": 122
        }, {
          "bob.5.4": 122
        }
      ]
    }
  }, {
    "bob": {
      "6.1": 11,
      "6.2": [
        {
          "6.2.1": 121
        }, {
          "6.2.2": 122
	      }
      ],
      "list": [
        {
          "bob.6.1": 121
        }
      ]
    }
  }
]

Only the `list` was required from objects called `bob`.

I was restricted to using ES5, so I came up with this:

const bobs = bob.reduce(function(a, c) {
  if (!!c.bob && !!c.bob.list) {
    Array.prototype.push.apply(a, c.bob.list)
  }
  return a
}, [])
console.log(bobs.length)

No comments:

Post a Comment