Issue
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"
}]
Solution
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);
Answered By - sabbir.alam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.