我有这个对象结构:
"users": {
"1": {
"id": 1,
"name": "John",
"email": "john@doe.com",
"supplier_id": 1,
"supplier_name": [
"Supplier1"
],
"supplier_code": "SUP001",
"count": "21"
}
}
我想更改它,使其看起来像这样:
"users": {
"1": {
"id": 1,
"name": "John",
"email": "john@doe.com",
"suppliers":[
{
"supplier_id": 1,
"supplier_name": [
"Supplier1"
]
}
],
"supplier_code": "SUP001",
"count": "21"
}
}
我尝试过这种方法,希望它能起作用:
const group = accumulator[item.id];
group.suppliers = [];
group.suppliers = group.suppliers.push(item.supplier_name, item.supplier_id, item.supplier_code);
return accumulator;
不幸的是,这似乎只是给了我一些被推入suppliers
的对象的信息,suppliers
不是数组,并且supplier_id
,supplier_name
和{{1} }在supplier_code
之外仍然可见:
suppliers
如何将其更改为所需的格式?
答案 0 :(得分:1)
您需要使用object
推送到suppliers
数组中。另外,删除不需要的旧密钥。
编辑-您可以直接创建1个对象的数组。谢谢@Adam
const group = accumulator[item.id];
group.suppliers = [{
supplier_id: item.supplier_id,
supplier_name: item.supplier_name,
supplier_code: item.supplier_code
}];
delete group.supplier_id;
delete group.supplier_name;
delete group.supplier_code;
return accumulator;
答案 1 :(得分:1)
您可以使用es6 Destructuring assignment,Object.values es2017(或改为Object.keys)。
如果您假设users
包含多个用户,则可以使用reduce。
在下面的示例中,原始对象不会发生突变。
希望有帮助
const original = {
"users": {
"1": {
"id": 1,
"name": "John",
"email": "john@doe.com",
"supplier_id": 1,
"supplier_name": [
"Supplier1"
],
"supplier_code": "SUP001",
"count": "21"
}
}
};
const { users } = original;
const reshaped = Object.values(users).reduce((acc, { id, supplier_id, supplier_name, ...rest }) => {
acc[id] = {
...rest,
suppliers: [{
supplier_id,
supplier_name: [supplier_name]
}]
};
return acc;
}, {});
console.log(reshaped);
答案 2 :(得分:-1)
这是一种快速而现代的解决方案:
const parseUsers = (users) => {
let parsedUsers = {};
for (key in users) {
const user = users[key];
// destructuring (or extracting) the relevant keys from the . user object, keeping everything else under 'rest'
const { supplier_id, supplier_name, ...rest } = user;
parsedUsers[key] = {
...rest, // spreading back our rest params
suppliers: [ // creating a new array and populating it with the keys which we previously extracted (along with their corresponding values)
supplier_id,
supplier_name
]
}
}
return parsedUsers;
}
用法:parseUsers(json.users)