Is it possible to flatten or remove the topmost key of an object? For example:
const obj = {
page: {
title: 'x',
images: {
0: {
src: '...'
}
}
}
}
So I can get:
{
title: 'x',
images: {
0: {
src: '...'
}
}
}
I tried with map
but the result isn’t what I am looking for:
const x = Object.keys(obj).map((key)=>{
return obj[key]
})
Any ideas?
4
Answers
You could take the values and assign to a new object.
You can simply achieve this by iterating the object keys.
Try this :
You can try this ..
This uses object destructuring to create a new object (flattenedObj) without the ‘page’ key. The original object obj remains unchanged. The resulting flattenedObj will have the structure you’re looking for:
All current answers create a new object. This one will modify the existing one
If assigning to another object is also ok, this simple approach will work too.
Be aware, that neither of these approaches deepclones you data. And they both assume the structure of the original data is ok (ie it’s an object with a single property at top level. And that property’s value is a valid object itself)