从javascript中现有的对象克隆新对象

时间:2018-11-16 20:52:04

标签: javascript rest object ecmascript-6 destructuring

我有一个像这样的多步骤javascript对象:

const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

,我想为其创建一个新副本。 我知道如果我使用类似let copy = { ...source };的东西,那就像是浅拷贝。因此,如果我更改source中的那些数组或对象,它们也将在copy中更改。

无论如何,通过解构,我可以获得所有项目的新副本吗?还是我应该像这样在每个级别上手动进行操作:

copy.prev = [...source.prev]
copy.current.list = [...source.current.list]
copy.current.data= [...source.current.data]

以此类推

4 个答案:

答案 0 :(得分:1)

有一种古老的方法,但仍然可以使用:

var cloned = JSON.parse(JSON.stringify(original));

答案 1 :(得分:1)

您可以使用JSON.stringify

    const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

newObj = JSON.parse(JSON.stringify(source));

答案 2 :(得分:1)

您可以这样解构:

const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

const {
current: {list: listClone, data: dataClone}
} = source

console.log(listClone, dataClone)

答案 3 :(得分:1)

With a simple object containing objects, arrays, and primitives, it's not that much code just to recursively clone everything.

Just return the primitives, map() the arrays, and reduce the object keys passing the values back in. Something like:

const source = {prev: [],current: {list: [{ a: 1, b: 2, c: 3 }],data: [{ c: 1, b: 2 }]},id: 12,next: []};

function clone(obj){
    return (typeof obj == 'object')
        ? (Array.isArray(obj))
            ? obj.map(i => clone(i)) 
            : Object.entries(obj).reduce((o, [key, value]) => 
              Object.assign(o, {[key]: clone(value)}), {})  
        : obj

}

let a_clone = clone(source)
console.log(JSON.stringify(a_clone, null, 2))


// is the clone deep? should be false
console.log(a_clone.prev === source.prev)
console.log(a_clone.current.list === source.current.list)