Home > Mobile >  create an array of objects from another array of objects using typescript with different key value p
create an array of objects from another array of objects using typescript with different key value p

Time:09-13

I have JSON format like this I not sure how do I create new array of objects from an different array of object

[
   {
      "description":"microsoftLocation",
      "icon":"Marker",
      "data_id":"123",
      "reference":"_1_microsoftOffice",
      "id":1,
      "text":"microsoftOffice"
   },
   {
      "description":"facebookOffice",
      "icon":"Marker",
      "data_id":"456",
      "reference":"_2_facebookOffice",
      "id":2,
      "text":"_2_microsoftOffice"
   },
]

I want the output to look something like this and not sure how to get the dynamic url as well

[
   {
      "url":"http://localhost:3000/layer?text=microsoftLocation&data_id=123",
      "text":"microsoftLocation",
      "active":true,
      "icon":Marker
   },
   {
      "url":"http://localhost:3000/layer?text=facebookOffice&data_id=123",
      "text":"facebookOffice",
      "active":true,
      "icon":Marker
   },
]

CodePudding user response:

You can do it using a map like this:

const data = [{
    "description": "microsoftLocation",
    "icon": "Marker",
    "data_id": "123",
    "reference": "_1_microsoftOffice",
    "id": 1,
    "text": "microsoftOffice"
  },
  {
    "description": "facebookOffice",
    "icon": "Marker",
    "data_id": "456",
    "reference": "_2_facebookOffice",
    "id": 2,
    "text": "_2_microsoftOffice"
  },
];

const newData = data.map(el => ({
  url: `http://localhost:3000/layer?text=${el.description}&data_id=${el.data_id}`,
  text: el.description,
  active: true,
  icon: el.icon
}));

console.log(newData);

CodePudding user response:

Just use map method in order to map from the original object properties to the new ones.

const array = [
   {
      "description":"microsoftLocation",
      "icon":"Marker",
      "data_id":"123",
      "reference":"_1_microsoftOffice",
      "id":1,
      "text":"microsoftOffice"
   },
   {
      "description":"facebookOffice",
      "icon":"Marker",
      "data_id":"456",
      "reference":"_2_facebookOffice",
      "id":2,
      "text":"_2_microsoftOffice"
   },
];

console.log(array.map(obj => ({ icon: obj.icon, active: true, text: obj.description, url: `http://localhost:3000/layer?text=${obj.description}&data_id=${obj.data_id}`})))

  • Related