Search code examples
javascriptarraysobjectunderscore.jsjavascript-objects

Dynamically create array of objects from the object with the array values


Currently I have the below object structure,

`let selectedOptions = {
  "color": {
    "id": "2",
    "values": [
      {
        "value": "red",
        "label": "Red",
        "id": 1
      },
      {
        "value": "blue",
        "label": "Blue",
        "id": 2
      }
    ]
  },
  "size": {
    "id": "19",
    "values": [
      {
        "value": "medium",
        "label": "Medium",
        "id": 2
      }
    ]
  },
  "demo": {
    "id": "19",
    "values": [
      {
        "value": "neylon",
        "label": "Neylon",
        "id": 2
      }
    ]
  }
  .
  .
  .
  N
}; `

And want to create array of objects from the above object like as below,

[
 { color: "red", size: "medium", demo: "neylon" },
 { color: "blue", size: "medium", demo: "neylon" }
]

I have tried like below but it didn't worked https://jsfiddle.net/6Lvb12e5/18/

let cArr = [];
for(key in selectedOptions) {
  selectedOptions[key].values.forEach(function(val,i) {
   cArr.push({ [key]: val.value  })
  })
}

Thanks


Solution

  • You could take the wanted parts, like color, size and demo and build a cartesian product out of the given data.

    const
        cartesian = (a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []),
        options = { color: { id: "2", values: [{ value: "red", label: "Red", id: 1 }, { value: "blue", label: "Blue", id: 2 }] }, size: { id: "19", values: [{ value: "small", label: "Small", id: 1 }, { value: "medium", label: "Medium", id: 2 }] }, demo: { id: "19", values: [{ value: "neylon", label: "Neylon", id: 2 }] } },
        parts = Object
            .entries(options)
            .map(([k, { values }]) => [k, values.map(({ value }) => value)]),
        keys = parts.map(([key]) => key),
        result = parts
            .map(([, values]) => values)
            .reduce(cartesian)
            .map(a => Object.assign(...a.map((v, i) => ({ [keys[i]]: v }))));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }