Home > Blockchain >  Destructuring objects with aliases at multiple levels
Destructuring objects with aliases at multiple levels

Time:07-27

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

CodePudding user response:

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.

CodePudding user response:

The following should work and follows some popular style guides:

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