Keep in mind that JSON stands for JavaScript Object Notation.
That means that any valid JSON is the stringified (or serialized) version of the JavaScript object.
That means we can simply create an in memory object directly from the JSON string like so: (limited example to keep it small)
let origJson = {
"name": "File",
"artist": "Andrew",
"attributes":
[
{
"trait_type": "Background",
"value": "Black"
}
]
}
Note, you need this first one to be an array of these so you really need to wrap your first JSON in an outer set of [ ] so you have an array of those that you can iterate over.
Like this...
let origJson = [{
"name": "File",
"artist": "Andrew",
"attributes":
[
{
"trait_type": "Background",
"value": "Black"
}
]
},
{
},
{
},
]
Once you've done that you need a class that represents your 2nd object -- the one that you are mapping to. You'll need to complete the object to insure every property can be initialized -- it was too much typing for me.
Also notice that you have some property names that have spaces & I've removed those spaces. Spaces won't work for property names. This NewObject class is just a representation of your second JSON example.
class NewObject
{
constructor(Background, Base, EyeType, EarType, TailType,
Headwear, MouthAccessories, EyeAccessories, EarAccessories,
Details, tokenId)
{
this.Background =Background;
this.Base = Base;
this.EyeType = ...
}
}
Once you have that, you can now iterate through the first object creating new instances of the NewObject. Something like the following.
let allNewObjects = [];
origJson.forEach((item) => {
allNewObjects.push (new NewObject(item.attributes[0].value, item.attributes[1].value, ...));
console.log(item.attributes[0].value, item.attributes[1].value);
});
Because I suggest the
origJson
be wrapped in outer [ ] it means that the loaded up variable
origJson
becomes an array of your original objects.
JavaScript arrays have a .forEach() method which will call a function for each item in the array -- passing each item in the array as an argument.
In my example I've implemented an arrow function that has two statements:
1. that maps to the new object
2. which outputs to the console.
Here's a fully working example:
class NewObject
{
constructor(Background, Base)
{
this.Background =Background;
this.Base = Base;
}
}
let origJson = [{
"name": "File",
"artist": "Andrew",
"attributes":
[
{
"trait_type": "Background",
"value": "Black"
},{
"trait_type": "Base",
"value": "White"
},
]
}]
let allNewObjects = [];
origJson.forEach((item) => {
allNewObjects.push (new NewObject(item.attributes[0].value, item.attributes[1].value));
console.log("attr 0: " + item.attributes[0].value, "attr 1: " + item.attributes[1].value);
});
If you know how to user your Browser's dev console you can even copy this code, open the dev console (F12 in most browsers) paste the code, hit <ENTER> and it will run and show output.