[英]Change key of and group javascript objects with lodash
我的对象结构如下:
{
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这样做,但没有成功,任何帮助赞赏! 试图寻找解决方案,但我不确定那些使它变得非常困难的术语。
使用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>
使用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>
试试这个,注意我已经使用过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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.