JS数组映射,groupBy键

时间:2019-03-01 10:16:19

标签: javascript arrays key

有人知道从中转换的干净解决方案吗?

    var foo1 = [
    {
    "value":"1",
    "key":"abc"
  },
  {
    "value":"2",
    "key":"abc"
  },
  {
    "value":"3",
    "key":"def"
  }
];

var foo2 = [
  {
    "value":["1","2"],
    "key":"abc"
  },
  {
    "value":"3",
    "key":"def"
  }
];
  • 您的帖子似乎主要是代码;请添加更多详细信息。

2 个答案:

答案 0 :(得分:0)

您可以使用数组reducefindIndexacc是累加器数组。在累加器数组中,使用findIndex查看是否存在具有相同键的对象。如果存在,则更新对象的值,否则在累加器数组中添加具有所需参数的新对象

var foo1 = [{
    "value": "1",
    "key": "abc"
  },
  {
    "value": "2",
    "key": "abc"
  },
  {
    "value": "3",
    "key": "def"
  }
];


let groupedBy = foo1.reduce(function(acc, curr) {
  let ifHasKey = acc.findIndex(function(item) {
    return item.key === curr.key;
  })

  if (ifHasKey === -1) {
    acc.push({
      value: [curr.value],
      key: curr.key
    })
  } else {
    acc[ifHasKey].value.push(curr.value)

  }

  return acc;


}, []);
console.log(groupedBy)

答案 1 :(得分:0)

您可以使用Map对项目进行分组,然后为结果集构建新对象。

var array = [{ value: "1", key: "abc" }, { value: "2", key: "abc" }, { value: "3", key: "def" }],
    grouped = Array.from(
        array.reduce((m, { key, value }) => m.set(key, [...(m.get(key) || []), value]), new Map),
        ([key, value]) => ({ key, value })
    );

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }