通过多个属性对数组中的元素进行分组

时间:2018-05-26 17:18:59

标签: javascript jquery arrays json grouping

我有这样的数组:

var arr = [
{"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
{"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
{"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
]

我想让一个新的数组看起来像这样:

[
  {
    "type": "color",
    "relation":[{"pid": "ITEM_1", "id": "ITEM_1_1"},
          {"pid": "ITEM_2", "id": "ITEM_2_2"}]
  }, {
    "type": "size",
    "relation":[{"pid": "DEFAULT_0", "id": ["DEFAULT_0_1","DEFAULT_0_2"]}]
  }
]

感谢。

========================================= 感谢Abrar的回答。我稍微调整它以分组相同的pid项目并得到我想要的结果。但是应该有更好的方法来做到这一点吗?

const arr = [
  {"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
  {"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
  {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
  {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];

const resultArr = [];
const groups =[];
arr.forEach((data) => {
  let type = data.type;
  let newArr = arr.filter(el => el.type === type);
  let resObj = {
    "type": type,
    "relation": []
  };

  newArr.forEach(el => {
    groups.push({"pid": el.pid, "id": el.id});
  });

            var group_to_values = groups.reduce(function(obj, item) {
                obj[item.pid] = obj[item.pid] || [];
                obj[item.pid].push(item.id);
                return obj;
            }, {});
            resObj.relation.push(group_to_values);

  if (resultArr.map(e => e.type).indexOf(type) < 0) {
    resultArr.push(resObj);
  }
})

console.log(resultArr); 

1 个答案:

答案 0 :(得分:0)

我已经重构了你的代码,现在它看起来像这样 -

const arr = [
  {"type":"color","pid":"ITEM_1","id":"ITEM_1_1"},
  {"type":"color","pid":"ITEM_2","id":"ITEM_2_2"},
  {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_1"},
  {"type":"size","pid":"DEFAULT_0","id":"DEFAULT_0_2"}
];


const resultArr = [];
arr.forEach((data) => {
  let type = data.type;
  let newArr = arr.filter(el => el.type === type);
  let resObj = {
    "type": type,
    "relation": []
  };
  newArr.forEach(el => {
    resObj.relation.push({"pid": el.pid, "id": el.id});
  });

  if (resultArr.map(e => e.type).indexOf(type) < 0) {
    resultArr.push(resObj);
  }
})

console.log(resultArr); //resultArr contains your desired output

基本上我已经根据type过滤掉了数组中的键,因为它必须是唯一的(根据你想要的输出)。这应该非常简单,不需要框架甚至jQuery。