Reputation: 323
I have a string of text, for example
"{"Date": 01/01/2019, "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}"
Also, I have an entity
function demo(first, second) {
this.first = first,
this.second = second
}
Is it possible to transform the string of text into the entity? For example,
"Date"
goes to first
01/01/2019
goes to second
"0"
goes to first
"John"
goes to second
Upvotes: 1
Views: 43
Reputation: 125
The Object.keys(json)
will do the trick in combination with the map
function:
const str = '{"Date": "01 / 01 / 2019", "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}';
const json = JSON.parse(str);
function demo(first, second) {
console.log(first, second);
this.first = first,
this.second = second
}
Object.keys(json).map(key => {
demo(key, json[key]);
});
Upvotes: 0
Reputation: 23545
You can create your own class
and then create objects iterating on your json object
class CustomObject {
constructor(x, y) {
this.first = x;
this.second = y;
}
}
// your initial data as a json into a string
const str = '{"Date": "01/01/2019", "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}';
// transform your string into a json object
const json = JSON.parse(str);
// Build the custom objects, using the data inside of the json object
// The notation [x, y] is called -> destructuring
const objs = Object.entries(json).map(([x, y]) => new CustomObject(x, y));
// Now that we have the objects, display the values stored inside
// each one of them, to show they are correctly settled
objs.forEach(x => console.log(x.first, x.second));
Upvotes: 3