0

I have some JSON loaded into JavaScript. The two objects have different formats. However, I want to copy the information from one to the other.

var myCollection = {
  name: '2007',
  items: [
    {
      name: 'item 1'
    }
  ]
};

var data = {
  path: 'somewhere',
  children: []
};

I want to copy all of the properties of the data object into the myCollection.items[0] object. In reality, data will have more properties. So, I'm trying to figure out how to do this as dynamically as possible instead of the brute force approach.

I was thinking to do

myCollection.items[0] = data;

In my head, this approach doesn't work though.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
JQuery Mobile
  • 6,221
  • 24
  • 81
  • 134

1 Answers1

2

Just push

myCollection.items.push(data);

or, if you can use ES6 and don't want to mutate structures, I think you could:

let newItems = [...myCollection.items, data]
let newObj = Object.assign({}, myCollection, {items: newItems})
Simon H
  • 20,332
  • 14
  • 71
  • 128