user2693928
user2693928

Reputation:

ES6 destructuring with dynamic object properties

I would like to know if the following is possible with ES6.

I have an object "o" with method:

get(name) { 
}

Which returns some other object depending on the provided name.

I have another function test like this:

function test(o) {

}

I wonder is there any way to destructur the paramaters with calliing get on the object.

For example: This is not working - it's the thing i want to do

// here is what I'm trying to do
function test({db: get('db')}) {

}
// this is working
function test(o) {
  var db = o.get('db');
}

I want "db" varaible to equal "o.get('db')". I can do it in the function body but I wonder if it's possible to make the it direclty in the argument definition.

So far I can use:

let [a, b, c] = [o.get('a'), o.get('b'), o.get('c')];

As first line in the function.

Thanks

Upvotes: 1

Views: 428

Answers (1)

georg
georg

Reputation: 214949

You can use getters instead of the generic get function. This would allow unpacking and also make the rest of the code easier to read:

let SomeObj = {
  get db() {
    return "this is db";
  }
}

function func({db}) {
  console.log('DB', db);
}

func(SomeObj);

If your properties are dynamic, you could do a horrible thing like this:

let SomeObj = {
  get(name) {
    return `this is ${name}`;
  }
}

function func(o, {db = o.get('db'), blah = o.get('blah')} = {}) {
  console.log('DB', db);
  console.log('blah', blah);
}

func(SomeObj);

but a more realistic option would be to have a function that maps get over an array of props:

let SomeObj = {
    get(name) {
        return `this is ${name}`;
    }
}

let extract = (obj, ...props) => props.map(p => obj.get(p));


function func(o) {
    let [db, blah] = extract(o, 'db', 'blah')

    console.log('DB', db);
    console.log('blah', blah);
}

func(SomeObj);

Finally, you can wrap your object in a Proxy to provide a dynamic getter, in which case simple destructuring will work out of the box:

let SomeObj = new Proxy({}, {
    get(obj, name) {
      if(name in obj)
        return obj[name];
      return `this is ${name}`;
    }
});

function func({db, blah}) {
    console.log('DB', db);
    console.log('blah', blah);
}

func(SomeObj);

Upvotes: 3

Related Questions