DDD
DDD

Reputation: 5

How to modify the key of {} to be a value of object Angular 8

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

Answers (2)

Nikhil
Nikhil

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

Tiep Phan
Tiep Phan

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

Related Questions