我有一个API调用返回的JSON数组
[{
"id": 1,
"name": "aa",
"zone": 1
}, {
"id": 2,
"name": "bb",
"zone": 1
}, {
"id": 3,
"name": "cc",
"zone": 2
}, {
"id": 3,
"name": "dd",
"zone": 2
}
]
通过使用lodash,我做了_.groupBy(myData,'zone')
,结果是一个包含2个数组的Object,每个数组用于不同的区域。
但我需要实现的是,在包含区域数组的对象中,以及每个区域包含一组关联名称。
期望的结果:
[
{
"zone": "1",
"items": [
{
"id": 1,
"name": "aa",
"zone": 1
},
{
"id": 2,
"name": "bb",
"zone": 1
}
]
},
{
"zone": "2",
"items": [
{
"id": 3,
"name": "cc",
"zone": 2
},
{
"id": 3,
"name": "dd",
"zone": 2
}
]
}
]
是否可以使用lodash将原始数组转换为我需要的数组?
稍后在我的Angular模板上,我想要*ngFor='let zone of zones'
或类似的
答案 0 :(得分:5)
假设你这样做了:
result = _.groupBy(myData,'zone')
在 lodash 功能之后添加:
result = Object.keys(result).map(key => ({ zone: key, items: result[key] }));
你会得到这个:
[
{
"zone": "1",
"items": [
{
"id": 1,
"name": "aa",
"zone": 1
},
{
"id": 2,
"name": "bb",
"zone": 1
}
]
},
{
"zone": "2",
"items": [
{
"id": 3,
"name": "cc",
"zone": 2
},
{
"id": 3,
"name": "dd",
"zone": 2
}
]
}
]
答案 1 :(得分:1)
你可以这样做:
let zones = _.chain(_.groupBy(myData, 'zone')).map(function (val, key) {
return {
zone: key,
names: _.map(val, "name") // Assuming you only need names. You can have the whole object too if needed
};
}).value();
这将产生:
[
{
"zone": "1",
"names": ["aa", "bb"]
},
{
"zone": "2",
"names": ["cc", "dd"]
}
]
答案 2 :(得分:1)
如果您要创建一个JSON对象,其中某些键具有区域值,并且相应的名称作为分配给该键的数组,
你可以使用lodash的 reduce
功能。只需:
_.reduce(myData, function(result, value, key) {
(result[value.zone] || (result[value.zone] = [])).push(value.name);
return result;
}, {});
代码将产生:
{"1":["aa","bb"],"2":["cc","dd"]}
var myData = [{
"id": 1,
"name": "aa",
"zone": 1
}, {
"id": 2,
"name": "bb",
"zone": 1
}, {
"id": 3,
"name": "cc",
"zone": 2
}, {
"id": 3,
"name": "dd",
"zone": 2
}];
console.log(JSON.stringify(
_.reduce(myData, function(result, value, key) {
(result[value.zone] || (result[value.zone] = [])).push(value.name);
return result;
}, {})
));

<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
&#13;
在这里您可以找到reduce
的lodash文档:
https://lodash.com/docs/4.17.4#reduce
答案 3 :(得分:0)
下面是我想要的实现,虽然没有Lodash(至少我认为你想要的。结果是一个数组数组,每个内部数组包含特定区域的每个原始对象。)
let originalArray = [{
"id": 1,
"name": "aa",
"zone": 1
}, {
"id": 2,
"name": "bb",
"zone": 1
}, {
"id": 3,
"name": "cc",
"zone": 2
}, {
"id": 3,
"name": "dd",
"zone": 2
}]
let transitionObject = {};
for (let i = 0; i < originalArray.length; i++) {
let currentObject = originalArray[i];
transitionObject[currentObject.zone] = transitionObject[currentObject.zone] || { names: []};
transitionObject[currentObject.zone].names.push(currentObject.name);
}
console.log(transitionObject);
&#13;