SeanPlusPlus
SeanPlusPlus

Reputation: 9033

Add an object to a deeply nested object

Let's say I have an object that looks like this:

const state = {
  meta: {
    attrs: [ 'dude' ],
    data: {
      foo: 'bar',
      stuff: [
        'x',
        'y',
      ]
    },
  },
}

And I want to add an object as a child to the data property, creating this:

const state = {
  meta: {
    attrs: [ 'dude' ],
    data: {
      foo: 'bar',
      stuff: [
        'x',
        'y',
      ],
      hello: 'world',
    },        
  },
}

Note, the addition of hello: 'world' as a child in the data object:

hello world as child

Using Object.assign I know that I can accomplish my task this way:

const hello = {
  hello: 'world',
}
const data = Object.assign(
  {},
  state.meta.data,
  hello,
)
const meta = Object.assign(
  {},
  state.meta,
  {
    data,
  },
)
const updatedState = Object.assign(
  {},
  state,
  {
    meta,
  },
)

Is it possible to accomplish this task using fewer Object.assign calls?

Upvotes: 0

Views: 44

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281656

You can do it using the spread operator syntax as well as

const state = {
  meta: {
    attrs: [ 'dude' ],
    data: {
      foo: 'bar',
      stuff: [
        'x',
        'y',
      ]
    },
  },
}

var data = {
    ...state, meta: {
        ...state.meta, data: {
            ...state.meta.data, hello: 'world'
        }
      }
}

console.log(data)

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138257

Object.assign(state.meta.data,{hello:"world"});

console.log(state);

Youre cloning each object of the tree which is unnecessary or could be done using JSON:

var cloned=JSON.parse(JSON.stringify(state));
Object.assign(cloned,{hello:"world"});

Upvotes: 0

Related Questions