I have a function which returns an object but I don’t like that I gotta declare it first and then do forEach method
JavaScript
x
10
10
1
export default (data) => {
2
const keysWithDotsObject = {};
3
Object.keys(data).forEach((keyWithDot) => {
4
Object.keys(data[keyWithDot]).forEach((key) => {
5
keysWithDotsObject[`${keyWithDot}.${key}`] = data[keyWithDot][key];
6
});
7
});
8
return keysWithDotsObject;
9
};
10
I think there should be something like this
JavaScript
1
9
1
export default (data) => {
2
const keysWithDotsObject = Object.keys(data).map((keyWithDot) => {
3
Object.keys(data[keyWithDot]).map((key) => ({
4
[`${keyWithDot}.${key}`]: data[keyWithDot][key],
5
}));
6
});
7
return keysWithDotsObject;
8
};
9
But for some reason, it doesn’t work.
PS: In this part —
JavaScript
1
2
1
[`${keyWithDot}.${key}`]
2
— I’m trying to create a key with a name separated by a dot (I don’t like that, but that’s what back-end wants me to)
Input :
JavaScript
1
5
1
Query1 = {
2
locus_ids: [25, 26],
3
microorganism_ids: [12],
4
};
5
Output :
JavaScript
1
3
1
Query1.locus_ids: [25, 26],
2
Query1.microorganism_ids: [12]
3
I also would like any suggestions on how to write more readable code
Advertisement
Answer
Did you consider using reduce
?
JavaScript
1
7
1
export default (data) => Object.keys(data).reduce((acc, keyWithDot) => (
2
Object.keys(data[keyWithDot]).forEach((key) => {
3
acc[`${keyWithDot}.${key}`] = data[keyWithDot][key];
4
}),
5
acc
6
), {});
7
You can also use Object.fromEntries
, map
and flatMap
should do the job:
JavaScript
1
7
1
export default (data) =>
2
Object.fromEntries(
3
Object.keys(data).flatMap((keyWithDot) =>
4
Object.keys(data[keyWithDot]).map((key) => [`${keyWithDot}.${key}`, data[keyWithDot][key]])
5
)
6
);
7
First, you build an array for each subentry, for each subentry, you flatten the array you got into an array of key/value, then with Object.fromEntries
, you make a new object!