0

I have a json object which has a zip entries. In the below json object there is zip entries under "Zipcode" key, basically I want to group it by Zip code to show which zip code belongs to what all zone Ids.

for example - zipcode 7 belongs to zoneIds 12005,12008,12006,12009 and zipcode 12 belongs to zoneIds 12004,11001. ultimate goal is to show this in some error message.

var Json = [{
City: "ABC",
ZipCode: "7",
ZoneID: 12008,
ZoneName: "test_TP41"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12005,
ZoneName: "test_TP4"
},
{City: "ABC",
ZipCode: "7",
ZoneID: 12007,
ZoneName: "test_TP456"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12006,
ZoneName: "test_TP5"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12009,
ZoneName: "testgrp16"},
{City: "CDE",
ZipCode: "12",
ZoneID: 12004,
ZoneName: "test_TP2"},
{City: "CDE",
ZipCode: "12",
ZoneID: 11001,
ZoneName: "test 20201"
}]
cSharp
  • 25
  • 1
  • 8

3 Answers3

0

you may follow this answer for further more classification

Using ES5+ ,

var grouped = _.mapValues(_.groupBy(Json , 'ZipCode'),
                          singleObject=> singleObject.map(item=> _.omit(Json , 'ZipCode')));

console.log(grouped);

Hope this would help you

0

You can loop through and create an object with ZipCode as key and ZoneID as value

const Json = [{
City: "ABC",
ZipCode: "7",
ZoneID: 12008,
ZoneName: "test_TP41"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12005,
ZoneName: "test_TP4"
},
{City: "ABC",
ZipCode: "7",
ZoneID: 12007,
ZoneName: "test_TP456"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12006,
ZoneName: "test_TP5"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12009,
ZoneName: "testgrp16"},
{City: "CDE",
ZipCode: "12",
ZoneID: 12004,
ZoneName: "test_TP2"},
{City: "CDE",
ZipCode: "12",
ZoneID: 11001,
ZoneName: "test 20201"
}];

const ZipMappedObj = {}

Json.forEach((k)=>{
if(ZipMappedObj[k.ZipCode]){
  ZipMappedObj[k.ZipCode].push(k.ZoneID)
} else {
ZipMappedObj[k.ZipCode] = [k.ZoneID]
}
})
console.log(ZipMappedObj)
Abishek Kumar
  • 519
  • 5
  • 13
0

You can do the following to get a structure like this,

obj = {
  ZipCode: [all the objects with this ZipCode],
}

Json = [{
City: "ABC",
ZipCode: "7",
ZoneID: 12008,
ZoneName: "test_TP41"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12005,
ZoneName: "test_TP4"
},
{City: "ABC",
ZipCode: "7",
ZoneID: 12007,
ZoneName: "test_TP456"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12006,
ZoneName: "test_TP5"},
{City: "ABC",
ZipCode: "7",
ZoneID: 12009,
ZoneName: "testgrp16"},
{City: "CDE",
ZipCode: "12",
ZoneID: 12004,
ZoneName: "test_TP2"},
{City: "CDE",
ZipCode: "12",
ZoneID: 11001,
ZoneName: "test 20201"
}]

const res = Json.reduce((acc, curr) => {
  if(acc.hasOwnProperty(curr.ZipCode)) {
    acc[curr.ZipCode].push(curr);
  } else {
    acc[curr.ZipCode] = [curr];
  }
  return acc;
}, {});

console.log(res);

If you want you can insert only the ZoneID in the array by doing this,

acc[curr.ZipCode] = [curr.ZoneID];

and

acc[curr.ZipCode].push(curr.ZoneID);
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30