jossefaz
jossefaz

Reputation: 3952

Destructuring an object from a dynamic string name

I got this config.json file :

"signs_table": {
  "id_field": "dummy_id_field_name",
  "prop" : "dummy_prop_name"
   ...
}

This file contains tons of configuration for huge amount of tables stored in a database. Every table has different field name but the configuration for my code is the same for each table (an Id field name, different property fields, but of course fields name changes from table to table).

So, in my code, I am getting a data object and I want to be able to destructs it to dynamically named properties (from the configuration) like so :

const { dummy_id_field_name, dummy_prop_name} = this.props.data

but this is hard coded way. I would like to load the named properties based on the configuration file. something like :

const IdField = config.get("signs_table").id_field // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const PropField = config.get("signs_table").prop
const { IdField , PropField } = data

Here the config.get("signs_table") line is a from a class method that manage my config.json file...it basically retrieves the property.

So far I found this usefull approach : ES6 — How to destructure from an object with a string key?

But this does not help me since I need to first retrieve the field name from the configuration file...

Any Idea ?

Upvotes: 0

Views: 1936

Answers (2)

ChrisG
ChrisG

Reputation: 2948

You can de-structure arbitrary property names as I'll show below, but the question is why are you forcing yourself into a syntax you are unfamiliar with. You should stick with the readable and straightforward approach instead of some fancy convoluted method.

const idField = config.get("signs_table").id_field; // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const propField = config.get("signs_table").prop;
const { [idField]: idValue, [propField]: propValue } = data;

It would be more straightforward to simply avoid the de-structuring altogether and access the fields directly.

const idField = config.get("signs_table").id_field; // this will retrieve the actual field name from config.json I want to be able to pass it through the destructuring operation
const propField = config.get("signs_table").prop;

const idValue = data[idField];
const propValue = data[propField];

Upvotes: 1

Bergi
Bergi

Reputation: 665070

You cannot avoid fetching the field names from the config files first:

const { id_field: IdField, pro: PropField } = config.get("signs_table"); // this will retrieve the actual field names from config.json 

Then, afterwards you can use those as computed property names when destructuring your actual data:

const { [IdField]: idValue , [PropField]: propValue } = this.props.data;
console.log(idValue, propValue);

Upvotes: 4

Related Questions