Coding Triumph

Helpful code snippets & tutorials

How to move inner object properties to the outer object in JavaScript

Have you ever come across a situation where you need to move all the properties of an inner object to the top level while keeping all the outer object properties in JavaScript? Well, it’s really simple, we can either use the old ES5 with Object.assign() or the new spread syntax of ES6.

1. With ES5 and Object.assign():

let outer = {
  a: 10,
  inner: {
    b: 120,
    c: 2
  }
};
outer = Object.assign(outer, outer.inner);
delete outer.inner
console.log(outer); // { a: 10, b: 120, c: 2 }

2. With ES6 and the spread syntax:

let outer = {
  a: 10,
  inner: {
    b: 120,
    c: 2
  }
};
outer = {...outer, ...outer.inner};
delete outer.inner
console.log(outer); // { a: 10, b: 120, c: 2 }
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments