Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

怎么使用 Lodash /Js 进行按对象字段分组处理

json对象

[
    dictprovinceVOList[{
    areaId: 13257
    cityAreaList:[
    {
        areaCode: "1853"
        areaId: 13265
        areaList: 
        firstLetter:"S"
        langType:"zh_CN"
        latitude:22.124049
        longitude:
        113.559954
        parentId:13257
        pinYin:"shengfangjigetangqu"
        postCode:"820008"
        sortValue:8
        title:"圣方济各堂区"
    },
    {
        ...
    }]
    parentId: 0
    sortValue: 34
    title:"澳门特别行政区"
   },{
    areaId:13238
    cityAreaList:[
    {
        areaCode: "1853"
        areaId: 13265
        areaList: 
        firstLetter:"S"
        langType:"zh_CN"
        latitude:22.124049
        longitude:
        113.559954
        parentId:13257
        pinYin:"shengfangjigetangqu"
        postCode:"820008"
        sortValue:8
        title:"圣方济各堂区"
    },{
        ...
    }]
    parentId:0
    sortValue:33
    title:"香港特别行政区"
   }]


]

得到以下结果。。分组依据是cityAreaList字段:firstLetter

{
   "iniData":"S",
   "cityAreaList":[
        {
          "areaCode":"1853","areaId": 372, ...
        },
        {...}
    ]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

lodash应该没有一步到位的函数

但有个groupBy函数可以用来分组

你可以用一个循环把所有城市的cityAreaList合到一个array

let array = [];
for(let city of citylist){
  array = array.contact(city.cityAreaList)
}

然后

_.groupBy(array,function(obj){
      return obj["firstLetter"];
  })

返回是一个object是大概是这种结构的

{
s:[
 {
   "areaCode":"1853","areaId": 372, ...},
 {...}
]
p:{
 ...
}
}

这个object的key就是你想要的"iniData"
剩下的事情就简单了

用Object.keys()获取object的所以key

let keys = Object.keys(object);
let newArr = [];
for(let key of keys){
newArr.push(
{
   "iniData":key,
   "cityAreaList":object[key]
}
)
}

这个newArr就是你想要的结果


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...