How to copy the properties of an inner object to the outer
By Flavio Copes
Learn how to copy the properties of an inner object up to the outer object in JavaScript using Object.assign, so you avoid copying each property by hand.
To copy the properties of an inner object to the outer one, use Object.assign(). Pass the outer object as the target and the inner object as the source, and every property moves up one level.
Here’s the problem I had. A tweet object, for some reason related to the architecture of the app, contained the actual tweet data in another object assigned to its data property:
let tweet = {
data: {
id: 1,
content: 'test'
}
}
I wanted those inner properties on the top level object:
let tweet = {
id: 1,
content: 'test'
}
I could write tweet.id = tweet.data.id and so on, but I didn’t want to copy each property by hand. The minute I add another property to data, I introduce a bug.
The solution
Here’s what I did:
tweet = Object.assign(tweet, tweet.data)
Object.assign() copies every property of the source (tweet.data) onto the target (tweet). It mutates the target, and it also returns it, so the reassignment above is not strictly needed. I kept it for clarity.
It’s the same technique you use to copy properties to another object, just applied in a slightly different way: here the target already contains the source.
Notice that the original data property is still there after the copy:
console.log(tweet)
//{ data: { id: 1, content: 'test' }, id: 1, content: 'test' }
If you don’t want it around, remove it:
delete tweet.data
Alternative: the spread operator
If you prefer creating a new object instead of mutating the existing one, use the spread operator:
tweet = { ...tweet, ...tweet.data }
The result is the same shape, but the original object is left untouched. Handy when you’re working with state you’re not supposed to mutate, like in React.
Watch out for name collisions
Be careful with one thing: if the outer object already has a property with the same name, the inner one wins. Object.assign() applies sources after the target, so the last value written stays.
Also, this is a shallow copy. If data contained a nested object, the outer object would get a reference to it, not a clone. Changing the nested object later changes it in both places. For flat data like this tweet, that’s not a problem.
Related posts about js: