对象是一成不变的吗?

时间:2019-04-13 04:51:26

标签: javascript immutability

我正在尝试展平和深化对象的副本。

这是我尝试如何做的一个例子:

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)

据我了解,嵌套对象仅链接到新对象,而不克隆。

如何在没有其他库的情况下正确执行操作?

3 个答案:

答案 0 :(得分:1)

您可以使用JSON.parse(JSON.stringify(obj))进行深层克隆

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)

答案 1 :(得分:0)

let new_object = Object.assign({}, your_object);

答案 2 :(得分:0)

使用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);

或者,使用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);