开发者问题收集

将嵌套数据结构转换为使用类对象

2016-11-12
34

我有以下内容:

476297875

]

但是,我希望用户成员成为类型用户的对象。因此,我希望将上述内容转换为以下内容:

182988444

]

javascript ES6转换我可以使用什么(转换应该应该)未明确提及 信息moreInfo )?在Python中,我可能会使用综合来做到这一点,但是JavaScript中的数组综合是非标准的。

2个回答

您可以循环遍历数据并更新属性,如下所示: x.user=new User(x.user)

注意:这将覆盖现有数组。

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())})

如果您希望创建一个新数组,请使用 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())})
Rajesh
2016-11-12

您可以使用解构并迭代数据。

function User({ firstName, lastName }){
    this.firstName = firstName,
    this.lastName = 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(o => o.user = new User(o.user));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
2016-11-12