使用数组值从对象动态创建对象数组

时间:2018-12-16 12:04:36

标签: javascript arrays object underscore.js javascript-objects

当前我具有以下对象结构,

`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
}; `

并希望从上述对象创建对象数组,如下所示,

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

我尝试过如下操作,但没有成功 https://jsfiddle.net/6Lvb12e5/18/

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

谢谢

2 个答案:

答案 0 :(得分:1)

您可以采用所需的部分,例如colorsizedemo,然后根据给定的数据构建笛卡尔积。

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; }

答案 1 :(得分:0)

我不确定这是否是执行此操作的最佳方法,即使数据丢失,但作为注释,它的发布量很大,但可以尝试:

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
      }
    ]
  }
}; 

let cArr = [];
var obj = {};
var glob;
for(key in selectedOptions) {
  selectedOptions[key].values.forEach(function(val,i) {
  obj[key] = val.value;
  }
)
  glob = obj;
}
cArr.push(glob);
console.log(cArr)