相同ID 做一组写法

var testdata = {0:{test_id:80,id:3},1:{test_id:80,id:2},3:{test_id:95,id:3},4:{test_id:95,id:4}};

用JS 写法,将两个相同的test_id 做为一组。得到以下的结果。

var result = {
80:[{test_id:80,id:3},{test_id:80,id:2}],
95:[{test_id:95,id:3}, {test_id:95,id:4}]
}

阅读 1.9k
2 个回答
    var b = {};
    result.forEach(function (obj) {
        var array = b[obj['id']] || [];
        array.push(obj);
        b[obj['id']] = array;
    });
    console.log(b);
var res = Object.keys(testdata).reduce((res, next) => {
  let item = testdata[next];
  let { test_id } = item;
  if (res[test_id]) {
    res[test_id].push(item);
  } else {
    res[test_id] = [item];
  }
  return res;
}, {});
console.log(res);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题