我有以下数据:
var data = {
"features": [
{
"properties": {
"route_id": 522,
"name": "the Mekong",
"tour_id": 538
}
},{
"properties": {
"route_id": 522,
"name": "Cambodia & the Mekong",
"tour_id": 545
}
},{
"properties": {
"route_id": 521,
"name": "Cambodia",
"tour_id": 537
}
}
]
}
现在,我想将具有类似"route_id"
的值分组为嵌套的对象数组;最终使用lodash;以便预期结果如下:
var result = {
"features": [
{
"properties": [{
"route_id": 522,
"name": "the Mekong",
"tour_id": 538
},{
"route_id": 522,
"name": "Cambodia & the Mekong",
"tour_id": 545
}]
},{
"properties": {
"route_id": 521,
"name": "Cambodia",
"tour_id": 537
}
}
]
}
我尝试使用_.group
,但我不知道如何在一个对象下获得嵌套数组。另请注意,"properties"
键会有其他键,但它们与结构无关。
如果features
集合中的对象包含一个密钥properties
,那么我强烈建议规范化结构,删除properties
密钥。不过,这是您可能正在寻找的实现。
var result = {
features: _(data.features)
// get all routes (get rid of properties key)
.map('properties')
// group by route_id
.groupBy('route_id')
// place properties key again
.map(function(group) { return { properties: group };})
// get grouped features
.value()
};
功能参考:lodash#map
,lodash#groupBy
var data = {
"features": [{
"properties": {
"route_id": 522,
"name": "the Mekong",
"tour_id": 538
}
}, {
"properties": {
"route_id": 522,
"name": "Cambodia & the Mekong",
"tour_id": 545
}
}, {
"properties": {
"route_id": 521,
"name": "Cambodia",
"tour_id": 537
}
}]
};
var result = {
features: _(data.features)
// get all routes (get rid of properties key)
.map('properties')
// group by route_id
.groupBy('route_id')
// place properties key again
.map(function(group) { return { properties: group };})
// get grouped features
.value()
};
console.log(result);
.as-console-wrapper{min-height:100%; top:0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
在jquery中你可以使用$ .extend(obj1,obj2);