0

I'm trying to flatten and deep copy of an object.

Here's an example of how I try to do:

const data = {
  firstObj: {
    data: 'Hi!',
    nestedArrayOfObject: [{
      name: 'hey',
      property: 'object'
    }],
  },
  secondObj: {
    name: 'second',
    nestedArray: []
  },
}

const object = {}
const keys = Object.keys(data)

for (let i = 0; i < keys.length; i += 1) {
  const items = Object.keys(data[keys[i]])

  for (let j = 0; j < items.length; j += 1) {
    object[items[j]] = data[keys[i]][items[j]]
  }
}

console.log(object)

As I understand, nested objects are being only linked to the new object, but not cloned.

How to do it correctly without additional libraries?

Andrey Osiyuk
  • 338
  • 7
  • 13

3 Answers3

1

You can use JSON.parse(JSON.stringify(obj)) to make a deep clone

const data = {
  firstObj: {
    data: 'Hi!',
    nestedArrayOfObject: [{
      name: 'hey',
      property: 'object'
    }],
  },
  secondObj: {
    name: 'second',
    nestedArray: []
  },
}

const object = {}
const keys = Object.keys(data)

for (let i = 0; i < keys.length; i += 1) {
  const items = Object.keys(data[keys[i]])

  for (let j = 0; j < items.length; j += 1) {
    object[items[j]] = JSON.parse(JSON.stringify(data[keys[i]][items[j]]))
  }
}

console.log(object)
Code Maniac
  • 35,187
  • 4
  • 31
  • 54
0
let new_object = Object.assign({}, your_object);
0

Use Object.assign:

const data = {
  firstObj: {
    data: 'Hi!',
    nestedArrayOfObject: [{
      name: 'hey',
      property: 'object'
    }],
  },
  secondObj: {
    name: 'second',
    nestedArray: []
  },
};
const object = Object.assign({}, data.firstObj, data.secondObj);

console.log(object);

Alternatively, use the spreading behaviour ... introduced in ECMAScript 6:

const data = {
  firstObj: {
    data: 'Hi!',
    nestedArrayOfObject: [{
      name: 'hey',
      property: 'object'
    }],
  },
  secondObj: {
    name: 'second',
    nestedArray: []
  },
};
const object = { ...data.firstObj, ...data.secondObj };

console.log(object);
Jack Bashford
  • 40,575
  • 10
  • 44
  • 74