I have this kind of and object:
obj: {
child1: [
{ type, checked, text, ... },
{ type, checked, text, ... },
{ type, checked, text, ... },
],
child2: [
{ type, checked, text, ... },
...
],
...
}
I need almost the same object, but child elements should have objects consisting only of type and checked values. Need my output to be like below example.
OUTPUT:
obj: {
child1: [
{
type: "type",
checked: "checked"
},
{
type: "type",
checked: "checked"
},
{
type: "type",
checked: "checked"
}
],
child2: [
{
type: "type",
checked: "checked"
}
]
}
So far everything I've tried doesn't seem to work.
My last failed attempt:
Object.keys(tabs).forEach(key =>
({
updatedState: {
[key]: (({ documentTypeId, checked }) => ({ documentTypeId, checked }))(tabs[key]),
},
}),
);
You can use Array.reduce()
to iterate the object's keys, with an inner Array.map()
and destructuring to create new objects from the properties you want to keep:
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)
You can use a combination of reduce (to iterate through the object keys) and map (for your children arrays)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With