0

Can anybody show me how to retrieve an object from JSON string. I'm stuck anh i really need help. For example i have an JSON string like this

 "traits": [
    {
      "trait_type": "type",
      "value": "Male",
      "display_type": null,
      "max_value": null,
      "trait_count": 6039,
      "order": null
    },
    {
      "trait_type": "accessory",
      "value": "Mohawk",
      "display_type": null,
      "max_value": null,
      "trait_count": 441,
      "order": null
    },
    {
      "trait_type": "accessory",
      "value": "Smile",
      "display_type": null,
      "max_value": null,
      "trait_count": 238,
      "order": null
    },
    {
      "trait_type": "accessory",
      "value": "2 attributes",
      "display_type": null,
      "max_value": null,
      "trait_count": 3279,
      "order": null
    }
  ],

And i wanna get some object like this

 "traits": [
   {
       "trait_type": "type",
      "value": "Male",
   },

   {
      "trait_type": "accessory",
      "value": "Mohawk",
   },
   {
     "trait_type": "accessory",
      "value": "Smile",
   },
   {
      "trait_type": "accessory",
      "value": "2 attributes",
   },
],

I hope if anybody can help me or give me some suggestion.

1 Answer 1

1

If you have a variable that contains the JSON string you would use JSON.parse();

I assume that you have your JSON in a file.

If you need to mutate existing object you can try this:

const traits = require('./your_JSON.json');

traits.map(trait => {
  delete element.display_type;
  delete element.max_value;
  delete element.trait_count;
  delete element.order;
})

If you want to save your object and create a new array with new data, use for loop:

const newArr = [];

for(let trait of traits) {
 newArr.push({"trait_type": trait.trait_type, "value": trait.value});
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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