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!

0

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

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 I'm not quite sure I understand what you mean. Consider creating a new question.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.