Home > other >  JavaScript select a portion of variables from object
JavaScript select a portion of variables from object

Time:10-04

here is by JS code:

var a = { depth: object_with_many_attributes.depth };

notice how depth appear twice, any standard way to rewrite by using depth just once?

CodePudding user response:

You can use Object Destructuring, but in that case, you need to define additional variables, like in an example

const object_with_many_attributes = { depth: 'xxx', 'somethingOther': 'qwerty'};

const { depth, somethingOther } = object_with_many_attributes;

const a = { depth, somethingOther };

CodePudding user response:

If depth must be used only once, you can destructure it with key:

// assignment
var object_with_many_attributes = { depth: 'foo', bar: 123 };

// destructure it:
var { 'depth' : a } = object_with_many_attributes;

console.log('object a:', { a }); // use as object later

  • Related