Javascript 按键对嵌套对象的lodash组数组
我有以下数据:Javascript 按键对嵌套对象的lodash组数组,javascript,arrays,data-structures,grouping,lodash,Javascript,Arrays,Data Structures,Grouping,Lodash,我有以下数据: var data = { "features": [ { "properties": { "route_id": 522, "name": "the Mekong", "tour_id": 538 } },{ "properties": { "route_id": 522, "name": "Cambodia & the Mekong
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\u 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
}
}
]
}
我试着使用
\uuu.group
,但我不知道如何获得一个对象下的嵌套数组。还要注意的是,除了“properties”
键之外,还有其他键,但它们与结构无关 在jquery中,可以使用$.extend(obj1、obj2) 如果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()
};
函数引用:
var数据={
“特点”:[{
“财产”:{
“路线识别号”:522,
“名称”:“湄公河”,
“旅游id”:538
}
}, {
“财产”:{
“路线识别号”:522,
“名称”:“柬埔寨和湄公河”,
“旅游id”:545
}
}, {
“财产”:{
“路线识别号”:521,
“名称”:“柬埔寨”,
“旅游id”:537
}
}]
};
var结果={
功能:(data.features)
//获取所有路由(删除属性键)
.map(“属性”)
//按路线编号分组
.groupBy('route_id'))
//再次放置属性键
.map(函数(组){return{properties:group};})
//获取分组的功能
.value()
};
控制台日志(结果)代码>
.as控制台包装{最小高度:100%;顶部:0;}
可能重复的是,它会对重复项进行分组,我在参考问题中实现了解决方案,但我无法在“属性”下得到嵌套数组的结果,就像我在结果中显示的那样like@IbrahimMohammed我建议与您的属性
保持一致,此时存在多个值,这是一个数组。如果它只有一个,那么它就是一个对象。你可能想考虑数组<代码>属性它是一致的,有一组特征,每个特征都有一个嵌套的“属性”对象,这是一个GEOJSON规范,但是我删除了一些密钥,使SimPiLARI不使用jQuery,我需要一个Load解决方案或香草JS。谢谢,这正是我需要的,我感谢您删除属性键的输入,但集合中还有其他键。我只是在我的代码片段中删除了它们,使之更简单。