hamid
hamid

Reputation: 31

use api info and equal it to an array

i have a json that i fetched from an api and pass it as props to a child component,i want use the data inside the json and loop through api, then set the data to an array like this:

    var myArray = [
{name : name-1, value: value-1}
{name : name-2, value: value-2}
              .
              .
              .
]

my api is like this:

[
{name : name-1, value:value-1, id:id-1, ... }
                     .
                     .
                     .
]

i know if i want return jsx i must use 'map' but what about this situation?

thank you

Upvotes: 1

Views: 39

Answers (1)

Volodymyr
Volodymyr

Reputation: 1408

You can use Array.prototype.map function here also:

 var dataFromAPI = [
  {name : 'name-1', value: 'value-1', id: 1},
  {name : 'name-2', value: 'value-2', id: 2},
  {name : 'name-3', value: 'value-3', id: 3},
];

var myArray = dataFromAPI.map(function (data) {
  return {
    name: data.name,
    value: data.value
  };
});

console.log(myArray);

or using ES6 syntax:

const dataFromAPI = [
  {name : 'name-1', value: 'value-1', id: 1},
  {name : 'name-2', value: 'value-2', id: 2},
  {name : 'name-3', value: 'value-3', id: 3},
];

const myArray = dataFromAPI.map(({name, value}) => ({ name, value }));

console.log(myArray);

Upvotes: 1

Related Questions