Reputation: 961
I have a requirement where I am querying in athena and getting back and api response like this in postman:
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "2453hsgdshgc",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-79.0303646}"
},
I want frame it some thing like below:
{
"768ch23sgcjh" : [
{
"gpsdate":"2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
{
"gpsdate":"2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
]
"2453hsgdshgc": [
{
"gpsdate":"2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
}
]
}
The above format I need.So basically if for a given id there are multiple set of items then id should be appeared once.
Upvotes: 0
Views: 398
Reputation: 22574
You can use array#reduce
to group objects based on id
.
const arr = [{ "id": "768ch23sgcjh", "gpsdate": "2019-04-06T13:02:08", "val1": "0.36233", "val2": "344", "loc": "{latitude=35.8374501, longitude=-49.0303646}" }, { "id": "768ch23sgcjh", "gpsdate": "2019-04-06T13:02:08", "val1": ".22", "val2": "145", "loc": "{latitude=35.8374501,longitude=-49.0303646}" }, { "id": "2453hsgdshgc", "gpsdate": "2019-04-06T13:02:08", "val1": "0.3030", "val2": "346", "loc": "{latitude=35.8374501, longitude=-79.0303646}" }],
result = arr.reduce((r, {id, ...rest}) => {
r[id] = r[id] || [];
r[id].push({...rest});
return r;
},{});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 442
let inputArray = [{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.36233",
"val2": "344",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "768ch23sgcjh",
"gpsdate": "2019-04-06T13:02:08",
"val1": ".22",
"val2": "145",
"loc": "{latitude=35.8374501, longitude=-49.0303646}"
},
{
"id": "2453hsgdshgc",
"gpsdate": "2019-04-06T13:02:08",
"val1": "0.3030",
"val2": "346",
"loc": "{latitude=35.8374501, longitude=-79.0303646}"
}
]
let outputArray = {};
for (let item of inputArray) {
if (!outputArray[item.id]) {
outputArray[item.id] = [{
gpsdate: item.gpsdate,
val1: item.val1,
val2: item.val2,
loc: item.loc
}]
} else {
outputArray[item.id].push({
gpsdate: item.gpsdate,
val1: item.val1,
val2: item.val2,
loc: item.loc
})
}
}
console.log(outputArray);
Upvotes: 1