0

I would like to extract an object from another object, and keep the extracted object as separate independent variable and have it no longer part of the first object. The following seems to do so but seems a little convoluted. What is the correct way to do so?

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]}}

1 Answer 1

1

Not exactly sure why you need to be doing this with the object keys but I would look at using Object.assign. Something like:

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 ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.