0

I have two arrays of objects:

    const osCapabilities = [{
      os: 'Windows',
      os_version: '10',
    }, {
      os: 'OS X',
      os_version: 'Mojave',
    }];

    const browserCapabilities = [{
      browser: 'chrome'
    }, {
      browser: 'firefox'
    }, {
      browser: 'internet explorer'
    }, {
      browser: 'safari'
    }];

I am trying to figure out the best way to combine them so I can get the following.

    const capabilities = [{
      browser: 'chrome',
      os: 'Windows',
      os_version: '10',
    }, {
      browser: 'chrome',
      os: 'OS X',
      os_version: 'Mojave',
    }, {
      browser: 'firefox',
      os: 'Windows',
      os_version: '10',
    }, {
      browser: 'firefox',
      os: 'OS X',
      os_version: 'Mojave',
    } ...
    ]

I cant wrap my head around how I can do this. Any help is greatly appreciated. Thanks!v

  • 1
    a simple nested forEach loop should do the trick, no need to try complicate it with array functions. Just go through every os, and for each one of them go through all browsers and build the combined objects to push into a result array. – Gibor Aug 15 '19 at 15:10
  • Can't you just write a nested loop to construct the objects you need, and then add them to a new array? (I'm sure you can do it with `reduce` too, but that would take me a bit more thought, and I'm not convinced it would be better in any sense.) – Robin Zigmond Aug 15 '19 at 15:10
  • 2
    @RobinZigmond it could possibly done with reduce, but yeah there's just no point in complicating it. Doing a nested loop would be way more readable and intuitive. – Gibor Aug 15 '19 at 15:11
  • You can do it with `Array.prototype.map()`, see my answer below. – Einar Ólafsson Aug 15 '19 at 15:24

1 Answers1

1

You can do this with Array.prototype.map and Array.prototype.flatMap()

var merged = browserCapabilities.flatMap(browser => {
    return osCapabilities.map(os => {
        return {...browser, ...os}
    })
})

First, you map out the browserCapabilities. In the map function, you map out also the osCapabilities and return arrays of objects with the os information for each browser.

You combine the browser object with the os object by spreading them into a new object. See spread syntax

The flatMap will then flatten what would otherwise be a two-dimensional array if you were using just .map() and flattens them into a one-dimensional array.

Einar Ólafsson
  • 3,036
  • 1
  • 19
  • 24