Search code examples
javascripttypescriptecmascript-6ecmascript-2016

Combine two arrays of objects to get all possible outcomes


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


Solution

  • 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.