我有这种对象:
obj: {
child1: [
{ type, checked, text, ... },
{ type, checked, text, ... },
{ type, checked, text, ... },
],
child2: [
{ type, checked, text, ... },
...
],
...
}
我需要几乎相同的对象,但子元素应该包含仅包含type和checked值的对象。需要我的输出如下例所示。
输出:
obj: {
child1: [
{
type: "type",
checked: "checked"
},
{
type: "type",
checked: "checked"
},
{
type: "type",
checked: "checked"
}
],
child2: [
{
type: "type",
checked: "checked"
}
]
}
到目前为止,我尝试过的所有内容似乎都不起作用。
我上次失败的尝试:
Object.keys(tabs).forEach(key =>
({
updatedState: {
[key]: (({ documentTypeId, checked }) => ({ documentTypeId, checked }))(tabs[key]),
},
}),
);
答案 0 :(得分:6)
您可以使用Array.reduce()
来迭代object's keys,使用内部Array.map()
和destructuring从您要保留的属性中创建新对象:
const type = 'type'
const checked = 'checked'
const text = 'text'
const obj = {
child1: [
{ type, checked, text },
{ type, checked, text },
{ type, checked, text },
],
child2: [
{ type, checked, text },
],
}
const result = Object.keys(obj).reduce((r, k) => {
r[k] = obj[k].map(({ type, checked }) => ({ type, checked }))
return r
}, {})
console.log(result)

答案 1 :(得分:2)
您可以使用reduce(迭代对象键)和map的组合 (为您的孩子阵列)
const obj = {
child1: [
{ type: 1, checked: true, text: 'aaa'},
{ type: 2, checked: false, text: 'bbb'},
{ type: 3, checked: true, text: 'ccc'}
],
child2: [
{ type: 4, checked: true, text: 'ddd'},
{ type: 5, checked: false, text: 'eee'},
{ type: 6, checked: true, text: 'fff'}
]
};
const result = Object.keys(obj).reduce((acc, key) => {
acc[key] = obj[key].map(child =>
({type: child.type, checked: child.checked}));
return acc;
}, {});
console.log(result);