我的对象结构如下:
{
guid x: { id: guid x, fooid: guid a, c: "baz"},
guid y: { id: guid y, fooid: guid a, c: "baz"},
guid z: { id: guid z, fooid: guid b, c: "baz"}
}
我想用fooid作为关键。然而,一些对象具有相同的fooid并且应该被分组(这里作为数组但也可以是对象):
{
guid a : [{ id: guid x, fooid: guid a, c: "bar"},{ id: guid y,
fooid: guid a, c: "bar"}],
guid b : { id: guid z, fooid: 3, c: "bar"}
}
我尝试用lodash这样做但没有成功,任何帮助表示赞赏!试图寻找解决方案,但我不确定那些使其变得非常困难的术语。
答案 0 :(得分:2)
使用lodash的_.groupBy()
:
var data = {
"guid x": { id: "guid x", fooid: "guid a", c: "baz"},
"guid y": { id: "guid y", fooid: "guid a", c: "baz"},
"guid z": { id: "guid z", fooid: "guid b", c: "baz"}
};
var result = _.groupBy(data, 'fooid');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 1 :(得分:1)
使用lodash我认为这就是你要找的东西
var data ={
1 : { id: 1, fooid: 200, c: "baz"} ,
2 : { id: 2, fooid: 200, c: "baz"} ,
3 : { id: 3, fooid: 300, c: "baz"} ,
}
var res = _(data)
.values()
.groupBy('fooid')
.value()
console.log(res)
.as-console-wrapper { max-height: 100%!important;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
答案 2 :(得分:0)
试试这个,请注意我已经使用过ES6语法
var obj = {
id1: { id: 1, fooid: 2, c: "baz"},
id2: { id: 2, fooid: 2, c: "baz"},
id3: { id: 3, fooid: 3, c: "baz"}
};
const newObj = Object.keys(obj).reduce((oldVal, newKey) => {
const key = 'fooid' + obj[newKey]['fooid'];
if(!oldVal.hasOwnProperty(key)){
oldVal[key] = [];
}
oldVal[key].push(obj[newKey])
return oldVal;
},{});
console.log(newObj);