Reputation: 69
I have such an object with nested object properties.
const obj = {
name: "name",
surname: "surname",
info: {
data: "info"
},
issue: {
data: "issue"
}
}
I exactly know the name of the fields with an object (info and issue), and the nested object format is always the same (data property).
I need to get such output:
const obj = {
name: "name",
surname: "surname",
info: "info",
issue: "issue"
}
Here you can see my solution:
const obj = {
name: "name",
surname: "surname",
info: {
data: "info"
},
issue: {
data: "issue"
}
}
const res = Object.entries(obj).reduce((acc, [k, v]) => v ? {...acc, [k]: typeof v === 'object' ? v.data : v} : acc , {})
console.log(res);
Is it good enough? As for me, such complex reduce doesn't look too much readably and can be simplified. Are there any simpler solutions?
Thank you!
Upvotes: 0
Views: 201
Reputation: 4592
almost identical to your, except avoiding type of
const obj = {
name: "name",
surname: "surname",
info: {
data: "info"
},
issue: {
data: "issue"
}
}
const res = Object.entries(obj).reduce((acc, [k, v]) => {
acc[k] = v.data || v;
return acc;
}, {})
console.log(res);
Upvotes: 0
Reputation: 1075239
reduce
is rarely a good option unless you're doing functional programming with predefined, tested reducer functions.
In this case, you don't even need a loop as you often would; just a simple object initializer with spread syntax does the job:
const res = {
...obj,
info: obj.info.data,
issue: obj.issue.data,
};
Live Example:
const obj = {
name: "name",
surname: "surname",
info: {
data: "info"
},
issue: {
data: "issue"
}
}
const res = {
...obj,
info: obj.info.data,
issue: obj.issue.data,
};
console.log(res);
Upvotes: 2