ram
ram

Reputation: 49

How can I load a key value pair array into state, by pulling data from a json file?

I am using an npm component React Sortable Tree to display some data that I am pulling from a .json file(data.json):

{
  info: "success",
  data: [
    {
      id: null,
      name: "Arizona",
      type: "REGION"
    },
    {
      id: null,
      name: "Alabama",
      type: "REGION"
    },
    // ...
  ]
}

The sortable tree component requires a treeData array in the state which is composed like this:

treeData: [
  {title: 'Arizona'},
  {title: 'Alabama'},
  // ...
]

But rather than hardcode these values, I want to pull them from the .json file. I've tried using a key value pair array, where the key is "title" and the value is data.data[i].name, but I am unable to push this onto the state:

setTree () {
  this.setState({
    {for(var i; i < data.data.length; i++){
      var title = "title";
      var name = data.data[i].name;
      var pushVal = {};
      pushVal[title] = name;
      treeData.push(pushVal);
    }}
  }
}

Upvotes: 0

Views: 180

Answers (2)

Joe Warner
Joe Warner

Reputation: 3452

There's two things you should look at the map prototype and decontructoring to make things simple

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

deconstructing is just picking arguments from the item passed.

and mapping over an array just loops over every item and returns a new array of modified items.

const json = {
  "data": [{
      "id": null,
      "name": "Arizona",
      "type": "REGION",
    },
    {
      "id": null,
      "name": "Alabama",
      "type": "REGION",
    }
  ]
}

const tree = json.data.map(({ name: title }) => ({ title }))

console.log(tree)

Upvotes: 1

hsz
hsz

Reputation: 152206

You can try with:

const treeData = data.data.map(item => ({ title: item.name }));

Upvotes: 2

Related Questions