javascript - How to use Lodash/Js to group by object fields
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-05-19 10:45:12
0
1
613

json object

[
    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:"香港特别行政区"
   }]


]

Get the following results. . The grouping is based on the cityAreaList field: firstLetter

{
   "iniData":"S",
   "cityAreaList":[
        {
          "areaCode":"1853","areaId": 372, ...
        },
        {...}
    ]
}
曾经蜡笔没有小新
曾经蜡笔没有小新

reply all(1)
Ty80

lodash should not have a one-step function

But there is a groupBy function that can be used for grouping

You can use a loop to combine the cityAreaList of all cities into an array

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

Then

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

The returned object is roughly of this structure

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

The key of this object is the "iniData" you want
The rest is simple

Use Object.keys() to get all keys of object

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

This newArr is the result you want

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!