Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map json data with array in react native

I have array like this in react native

 const data = [
    { key: 1, label: 'Service1'},
    { key: 2, label: 'Service2' },
    { key: 3, label: 'Service3' },
    { key: 4, label: 'Service4' },
    { key: 5, label: 'Service4' },
 ];

and json data:

 "services": [
    {
      "id": 1,
      "name": "Hotels",
    },
    {
      "id": 2,
      "name": "Embassies",
    },
 ]

How to map id to key and name to label???

like image 446
Sugeivan Senthinathan Avatar asked Feb 07 '23 11:02

Sugeivan Senthinathan


2 Answers

You want to fill your const data with values from JSON, correct?

Try this:

var jsonData = {
  "services": [
    { "id": 1, "name": "Hotels" },
    { "id": 2, "name": "Embassies" }
  ]
};

var data = jsonData.services.map(function(item) {
  return {
    key: item.id,
    label: item.name
  };
});

console.log(data);
like image 187
lalkmim Avatar answered Feb 10 '23 22:02

lalkmim


if your data like below (removed services key)

var jsonData = [
    { "id": 1, "name": "Hotels" },
    { "id": 2, "name": "Embassies" }
  ];

var data = jsonData.map(function(item) {
  return {
    key: item.id,
    label: item.name
  };
});

console.log(data);
like image 37
Sandhya Deshmukh Avatar answered Feb 10 '23 22:02

Sandhya Deshmukh