Baz Baz - 26 days ago 6
Javascript Question

Convert a nested data structure to use a class object

I have the following:

data = [
{
"user":{"firstName":"John","lastName":"Doe"},
"info":{"x":1,"y":2},
"moreInfo":{"name":"johns12info"}
},
{
"user":{"firstName":"John","lastName":"Doe"},
"info":{"x":2,"y":2},
"moreInfo":{"name":"johns22info"}
},
{
"user":{"firstName":"Mary","lastName":"Doe"},
"info":{"x":2,"y":2},
"moreInfo":{"name":"marys22info"}
}


]

However, i wish for the user members to be objects of type User. So I wish to convert the above to the following:

data = [
{
"user":User({"firstName":"John","lastName":"Doe"}),
"info":{"x":1,"y":2},
"moreInfo":{"name":"johns12info"}
},
{
"user":User({"firstName":"John","lastName":"Doe"}),
"info":{"x":2,"y":2},
"moreInfo":{"name":"johns22info"}
},
{
"user":User({"firstName":"Mary","lastName":"Doe"}),
"info":{"x":2,"y":2},
"moreInfo":{"name":"marys22info"}
}


]

What javascript ES6 conversion can I use that is tidy and robust (the conversion should not explicitly mention
info
or
moreInfo
)? In python I would probably have used comprehensions to do this but Array comprehensions in javascript are non standard.

Answer

You can loop over data and update the property as x.user=new User(x.user)

Note: this will override existing array.

function User(obj) {
  this.firstName = obj.firstName;
  this.lastName = obj.lastName;
  this.fullName = () => {
    return this.firstName + " " + this.lastName
  }
}

var data = [{ "user": { "firstName": "John", "lastName": "Doe" }, "info": { "x": 1, "y": 2 }, "moreInfo": { "name": "johns12info" } }, { "user": { "firstName": "John", "lastName": "Doe" }, "info": { "x": 2, "y": 2 }, "moreInfo": { "name": "johns22info" } }, { "user": { "firstName": "Mary", "lastName": "Doe" }, "info": { "x": 2, "y": 2 }, "moreInfo": { "name": "marys22info" } }];

data.forEach(x => {
  x.user = new User(x.user);
});

data.forEach(x=>{console.log(x.user.fullName())})

If you wish to create a new array, use array.map

function User(obj) {
  this.firstName = obj.firstName;
  this.lastName = obj.lastName;
  this.fullName = () => {
    return this.firstName + " " + this.lastName
  }
}

var data = [{ "user": { "firstName": "John", "lastName": "Doe" }, "info": { "x": 1, "y": 2 }, "moreInfo": { "name": "johns12info" } }, { "user": { "firstName": "John", "lastName": "Doe" }, "info": { "x": 2, "y": 2 }, "moreInfo": { "name": "johns22info" } }, { "user": { "firstName": "Mary", "lastName": "Doe" }, "info": { "x": 2, "y": 2 }, "moreInfo": { "name": "marys22info" } }];

var pData = data.map(x => {
  x.user = new User(x.user);
  return x;
});

pData.forEach(x=>{console.log(x.user.fullName())})