简体   繁体   中英

Destructuring objects with aliases at multiple levels

Let's say I have this object:

const job = {
  input_schema: {
    properties,
    ...
    },
  ...
};

and I need to access input_schema and properties but I'd like to assign both of them to an alias. How can I assign inputSchema and fields aliases with only one destructuring?

const { input_schema: inputSchema } = job;
const { properties: fields } = input_schema

You can define multiple aliases for different levels by accessing the same property multiple times.

const {
  input_schema: inputSchema,
  input_schema: {properties: fields}
} = job;

Full working example:

 const job = { input_schema: { properties: { someProp: null, }, }, }; const { input_schema: inputSchema, input_schema: { properties: fields } } = job; console.log(inputSchema, fields);


Regarding your question what the best approach is: I think this is quite opinion based or simply personal preference. It also doesn't make a big difference for your particular use case.

The following should work and follows some popular style guides:

const { input_schema: inputSchema } = job;
const { properties: fields } = inputSchema;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM