As I asked above in the comments; why do you think you want to do this?
If it is because you actually want to access the object using a dot delimited string
const name = { sample: { name: "joe", age: 69 } }['sample.name'];
then see: Convert a JavaScript string in dot notation into an object reference.
Be warned that the accepted answer offers a long explanation as to why that is bad practice (and if the accessing is, then the remapping as you've illustrated certainly is worse).
If having read that answer you still feel that you need to remap and flatten the object then you may as well make it work for arbitrarily deep objects.
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 generic typeof v === 'object'
check will match a number of built-in objects such as Date
and null
, and will also match arrays, so you may need to narrow it. see: Check if a value is an object in JavaScript