我有以下内容:
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"}
}
但是,我希望用户成员是User类型的对象。所以我希望将上述内容转换为以下内容:
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"}
}
我可以使用哪种javascript ES6转换,整洁且健壮(转换不应明确提及info
或moreInfo
)?在python中,我可能会使用理解来做到这一点,但是javascript中的数组理解是非标准的。
答案 0 :(得分: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())})
答案 1 :(得分:0)
您可以使用解构并迭代数据。
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; }