1

I have a React component which is performing an axios.get call on JSON file on componentDidMount. The JSON has an object with an embedded object, like so:

This is the initial format:

  "objects": {
      "5bd4a1a4-f806-4355-bf34-1b4054c2881e": {
         "type": "tosca.resourceTypes.TPE",
         "label": "BVI 610",
         "value": "801070217_BVI610"
        },

and this is the console.log after my initial axios.get call.

5bd4a1a0-fd74-4a9f-b7e2-c5ab15360839: {type: "tosca.resourceTypes.TPE", label: 
"Bundle-Ether 33", value: "801070217_Bundle-Ether33"}

So I could succesfully get a list of the first item using:

const finalTree = Object.keys(fullTree).map(({item}) => ({id: fullTree[item]}));

but what I need to do is convert finalTree into an array which also contains the type, label and value for each item and then put that into state. I have been messing with jsonQuery but it's not working for me and I'm a relative noobie when it comes to manipulating JSON data. Thanks in advance for any help!

CHays412
  • 145
  • 2
  • 15

2 Answers2

1

You can use Object.keys to get an array of all the keys, and map that array and create a new object for each key that contains all the fields in its object and the key.

Example

const obj = {
  "5bd4a1a4-f806-4355-bf34-1b4054c2881e": {
    "type": "tosca.resourceTypes.TPE",
    "label": "BVI 610",
    "value": "801070217_BVI610"
  }
};

const result = Object.keys(obj).map(key => ({
  ...obj[key],
  id: key
}));

console.log(result);
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • Hey Tholle is you happen to see this one other question ... how can I give the entire sub-array that is output from your code a label called "ports"? – CHays412 Nov 05 '18 at 12:30
  • @CHays412 I'm not quite sure I understand what you mean. Consider creating a new question. – Tholle Nov 05 '18 at 12:53
0

const obj = {
  "5bd4a1a4-f806-4355-bf34-1b4054c2881e": {
    "type": "tosca.resourceTypes.TPE",
    "label": "BVI 610",
    "value": "801070217_BVI610"
  }
};

const result = Object.keys(obj).map(key => ({
  ...obj[key],
  id: key
}));

console.log(result);
CHays412
  • 145
  • 2
  • 15