Search code examples
javascriptarraysnode.jsjsonjavascript-objects

Creating custom json objects using changeable number of variables


I have this json object:

[
  {
    "trip": [
      {
        "place": {
          "id": 8,
          "name": "New York",
        },
        "group": 1
      }
  },
  ...
]

I can have a N number of groups, so i need to create an array of objects like this:

[
   {
     "group1": "New York",
     "group2": "Los Angeles",
     "group3": "Rome",
     ...
   }
]

Each group is called groupX where X is a number taken from every "group" instance in every object in the first array and his value must be taken from "name" instance in every object in the first array.

How can i do it? Thanks in advance!


Solution

  • .map() is handy for getting an array of results, applying a function to each element of an existing array. Something like this:

    var obj = [{
        "trip": [{
          "place": {
            "id": 8,
            "name": "New York",
          },
          "group": 1
        }]
      },
      {
        "trip": [{
          "place": {
            "id": 8,
            "name": "london",
          },
          "group": 2
        }]
      },
      {
        "trip": [{
          "place": {
            "id": 8,
            "name": "tokyo",
          },
          "group": 3
        }]
      },
    ]
    var result = obj.map((array_element) => {
      let group = "group" + String(array_element['trip'][0]['group'])
      let place = String(array_element['trip'][0]['place']['name'])
      let to_return = {};
      to_return[group] = place
      return to_return;
    })
    console.log(result)
    /*
    [
    { "group1": "New York" },
    { "group2": "london" },
    { "group3": "tokyo" }
    ]
    */