我想从另一个对象中提取一个对象,并将提取的对象保持为单独的独立变量,并使其不再是第一个对象的一部分。以下似乎是这样做但似乎有点复杂。这样做的正确方法是什么?
function printIt(name,o) {
//Do this way so I can see what object was at given time.
console.log(name,JSON.stringify(o))
}
var o = {
a: 123,
b: {
a: 111,
b: 222,
c: [3, 2, 1]
},
c: {
a: 321,
b: 123,
c: [1, 2, 3]
}
};
printIt("o0", o);
var o_b = o.b;
printIt("o_b1", o_b);
printIt("o1", o);
o_b.a = 444;
o.b.c=666;
printIt("o_b2", o_b);
printIt("o2", o);
delete o.b;
printIt("o_b3", o_b);
printIt("o3", o);
https://jsfiddle.net/zn0asewb/1/
o0 {"a":123,"b":{"a":111,"b":222,"c":[3,2,1]},"c":{"a":321,"b":123,"c":[1,2,3]}}
o_b1 {"a":111,"b":222,"c":[3,2,1]}
o1 {"a":123,"b":{"a":111,"b":222,"c":[3,2,1]},"c":{"a":321,"b":123,"c":[1,2,3]}}
o_b2 {"a":444,"b":222,"c":666}
o2 {"a":123,"b":{"a":444,"b":222,"c":666},"c":{"a":321,"b":123,"c":[1,2,3]}}
o_b3 {"a":444,"b":222,"c":666}
o3 {"a":123,"c":{"a":321,"b":123,"c":[1,2,3]}}
答案 0 :(得分:1)
不完全确定为什么需要使用对象键执行此操作,但我会考虑使用Object.assign
。类似的东西:
var o = {
a: 123,
b: {
a: 111,
b: 222,
c: [3, 2, 1]
},
c: {
a: 321,
b: 123,
c: [1, 2, 3]
}
};
var b = Object.assign({}, o.b)
delete o.b;
console.log(o) // { a: 123, c: { a: 321, b: 123, c: [ 1, 2, 3 ] } }
console.log(b) // { a: 111, b: 222, c: [ 3, 2, 1 ] }