Can you explain the reason behind wanting to do this?
If it's because you're aiming to access the object using a dot delimited string,
const name = { sample: { name: "joe", age: 69 } }['sample.name'];
you can refer to: Convert a JavaScript string in dot notation into an object reference.
Please note that the recommended approach explains why this might not be considered a good practice (and if direct access is problematic, then the remapping as shown could be even worse).
If after reading the explanation you still believe that you absolutely have to remap and flatten the object, you should aim to make it work for objects of any depth.
const input = {
sample: {
name: 'joe',
age: 69,
favorite: {
food: 'pie',
colors: ['pink', 'yellow']
},
birthday: (new Date(1980, 2, 18)) // excluded from result because Object.entries(Date).length === 0
}
};
function recursivelyCombineKeys(obj) {
const res = {};
for (const [k, v] of Object.entries(obj)) {
if (typeof v === 'object') {
for (const [_k, _v] of Object.entries(recursivelyCombineKeys(v))) {
res[`${k}.${_k}`] = _v
}
} else {
res[k] = v
}
}
return res
}
console.log(recursivelyCombineKeys(input));
Note: The general typeof v === 'object'
check covers various built-in objects like Date
and null
, including arrays, so you may need to specify it further. See more at: Check if a value is an object in JavaScript