gpt4 book ai didi

javascript - 返回新形式的数组 - javascript

转载 作者:行者123 更新时间:2023-11-30 14:22:25 25 4
gpt4 key购买 nike

我的数据:

{
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
},
{
"id": 7,
"code": "airtel121",
"position": null,
"salary": null,
"login": {
"id": 8,
"username": "annamalai",
"firstName": "Anna",
"lastName": "malai",
"code": "airtel121",
}
}
]
}

我的预期结果:

{
"rows": [
{
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
"staffs": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
}
]
},
{
"id": 8,
"username": "annamalai",
"firstName": "Anna",
"lastName": "malai",
"code": "airtel121",
"staffs": [
{
"id": 7,
"code": "airtel121",
"position": null",
"salary": null",
}
]
}
]
}

我试过了,但只有我得到第一个对象,检查我的 fiddle :

http://jsbin.com/qaqehakuwi/edit?js,output

这可以使用 for 循环进行循环还是可以通过 lodash 完成?

检查我上面的 jsbin 链接以获取代码。

我在我的项目中使用 ES6 编码方式,所以我使用了扩展运算符。

最佳答案

您可以使用 map 从旧对象的 rows 数组创建新对象的 rows 数组:

let newObj = {
rows: oldObj.rows.map(row => { // map the rows of the old object into the rows of the new object
let { login, ...rest } = row; // for each object/row get the login object as 'login' and the rest of the props as 'rest'
return { ...login, staffs: [rest] }; // return a new object that has the props of 'login' and an additional prop 'staffs' which is an array containing 'rest'
})
};

示例:

let oldObj = {"rows":[{"id":3,"code":"airtel121","position":"manager","salary":"25000","login":{"id":4,"username":"sameer","firstName":"Mohamed","lastName":"Sameer","code":"airtel121"}},{"id":7,"code":"airtel121","position":null,"salary":null,"login":{"id":8,"username":"annamalai","firstName":"Anna","lastName":"malai","code":"airtel121"}}]};

let newObj = {
rows: oldObj.rows.map(row => {
let { login, ...rest } = row;
return { ...login, staffs: [rest] };
})
};

console.log(newObj);

关于javascript - 返回新形式的数组 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com