Reputation: 5
I'm hoping to rearrage the key to be part of the object element.
{
123: [ {geoLong: 323, geoLat:4234}, {geoLong: 325, geoLat: 3422} ],
349: [ {geoLong: 768, geoLat:456},
{geoLong: 7234, geoLat: 590},
{geoLong: 7234, geoLat: 590} ],
958: [ {geoLong: 643, geoLat:290},
{geoLong: 567, geoLat: 378}],
...
}
To be something like the below result before I deflatten the object.
{
123: [ {geoLong: 323, geoLat:4234, id: 123},
{geoLong: 325, geoLat: 3422, id: 123} ],
349: [ {geoLong: 768, geoLat:456, id: 349},
{geoLong: 7234, geoLat: 590, id: 349},
{geoLong: 7234, geoLat: 590, id: 349} ],
958: [ {geoLong: 643, geoLat:290, id: 958},
{geoLong: 567, geoLat: 378, id: 958}],
...
}
Upvotes: 0
Views: 2422
Reputation: 6643
You can use Object.keys() and map() to do that.
var data = { 123: [ {geoLong: 323, geoLat:4234}, {geoLong: 325, geoLat: 3422} ], 349: [ {geoLong: 768, geoLat:456}, {geoLong: 7234, geoLat: 590}, {geoLong: 7234, geoLat: 590} ], 958: [ {geoLong: 643, geoLat:290}, {geoLong: 567, geoLat: 378}] };
Object.keys(data).forEach(key => {
// Filter 'undefined' and 'null' values.
data[key] = data[key].filter(item => item);
data[key] = data[key].map(item => {
item.id = key;
return item;
});
});
console.log(data);
Upvotes: 0
Reputation: 12596
You could loop through object with Object.entries method.
obj = {
123: [ {geoLong: 323, geoLat:4234}, {geoLong: 325, geoLat: 3422} ],
349: [ {geoLong: 768, geoLat:456},
{geoLong: 7234, geoLat: 590},
{geoLong: 7234, geoLat: 590} ],
958: [ {geoLong: 643, geoLat:290},
{geoLong: 567, geoLat: 378}],
}
Object.entries(obj).forEach(([key, values]) => {
values.forEach(item => item.id = (+key));
})
Result:
{
"123": [
{
"geoLong": 323,
"geoLat": 4234,
"id": 123
},
{
"geoLong": 325,
"geoLat": 3422,
"id": 123
}
],
"349": [
{
"geoLong": 768,
"geoLat": 456,
"id": 349
},
{
"geoLong": 7234,
"geoLat": 590,
"id": 349
},
{
"geoLong": 7234,
"geoLat": 590,
"id": 349
}
],
"958": [
{
"geoLong": 643,
"geoLat": 290,
"id": 958
},
{
"geoLong": 567,
"geoLat": 378,
"id": 958
}
]
}
Upvotes: 1