JavaScript将具有特定结构的对象转换为数组

时间:2018-08-30 16:44:05

标签: javascript arrays object

预期输入:

const all = [
       {  "Attribute_Values" : [ "36", "38", "40" ],
          "Attribute" : "size"
       }, 
       {  "Attribute_Values" : [ "blue", "black" ],
          "Attribute" : "color"
       }
    ];

预期输出:

[ {size: '36', color: 'blue'},
  {size: '36', color: 'black'},
  {size: '38', color: 'blue'},
  {size: '38', color: 'black'}, 
  {size: '40', color: 'blue'},
  {size: '40', color: 'black'} ]

3 个答案:

答案 0 :(得分:4)

首先生成带有所需键和值的对象,然后采用递归函数,该函数将所有键/值对分离,并通过迭代值来构建新的笛卡尔积,如果具有对象的数组再次调用const all = [ { "Attribute_Values" : [ "36", "38", "40" ], "Attribute" : "size" }, { "Attribute_Values" : [ "blue", "black" ], "Attribute" : "color" } ]; let results = []; all[0].Attribute_Values.forEach(size => { all[1].Attribute_Values.forEach(color => { results.push({size: size, color: color}); }); }); console.log(results); 并构建新对象。

这同样适用于嵌套对象。

getCartesian
function getCartesian(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        var temp = [];
        r.forEach(s =>
            (Array.isArray(v) ? v : [v]).forEach(w =>
                (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
                    temp.push(Object.assign({}, s, { [k]: x }))
                )
            )
        );
        return temp;
    }, [{}]);
}

var all = [{ Attribute_Values: ["36", "38", "40"], Attribute: "size" }, { Attribute_Values: ["blue", "black"], Attribute: "color" }],
    temp = Object.assign(...all.map(({ Attribute_Values, Attribute }) => ({ [Attribute]: Attribute_Values }))),
    cartesian = getCartesian(temp);

console.log(temp);
console.log(cartesian);

答案 1 :(得分:1)

我将使用一个笛卡尔积生成器,该生成器获取属性值,并在填充结果时从产品当前位置读取属性名称。生成器来自here

const all = [
       {  "Attribute_Values" : [ "36", "38", "40" ],
          "Attribute" : "size"
       }, 
       {  "Attribute_Values" : [ "blue", "black" ],
          "Attribute" : "color"
       }
    ];

// Cartesian generator - copied from https://stackoverflow.com/a/44012184/3820185
function* cartesian(head, ...tail) {
  const remainder = tail.length > 0 ? cartesian(...tail) : [[]];
  for (let r of remainder) for (let h of head) yield [h, ...r];
}

let result = [], part, product, i;

for(product of cartesian(...all.map(i => i.Attribute_Values))) {
  part = {};
  for(i = 0; i < product.length; i++) part[all[i].Attribute] = product[i];
  result.push(part);
}

console.log(result);

答案 2 :(得分:0)

您可以遍历size数组,然后通过遍历colors数组将每种尺寸与每种颜色组合起来。

plyr::ldply(Item_list, rbind)