0

Thank you for your guidance.

I'd like to find a simple way of passing function arguments, to populate a de-structured variable. Hit a stumbling block, is this possible? As I'd like to then use a Rest... operator and tidy up my code - it is an incredible syntax if possible.

This Works:

let cat = {
    Models: {
        brand: ['sku1', 'sku2', 'sku3', 'sku4', 'sku5']
    }
};
let {brand} = cat.Models;
for (let [key,value] of Object.entries(brand)) {
    console.log(`${key} ${value}`)
};

This does not:

function wrapper(b) {
    let {b} = skus.Models;
    for (let [key,value] of Object.entries(b)) {
        console.log(`${key} ${value}`)
    };
}
wrapper('brand');
dimButTries
  • 661
  • 7
  • 15
  • 2
    check the code you posted, it seems it's not , you are recedlaring a variable b and you are referring to an undeclared variable skus – PA. May 25 '20 at 11:47

1 Answers1

1

You can destructure a dynamic key but you need to give it a different name like

function wrapper(b) {
    let {[b]: model} = skus.Models;
    for (let [key,value] of Object.entries(model)) {
        console.log(`${key} ${value}`)
    };
}
wrapper('brand');
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • 1
    many, many thanks for your swift response and accurate answer. It is incredibly helpful. I just stumbled across the de-structuring syntax and was not familiar with ```{[b]: model}``` notion. Appreciate your guidance, I learnt something new today. Have a great day. – dimButTries May 25 '20 at 11:54
  • This works fine but I would argue there's now no improvement on the "old-fashioned" way of doing this: `let model = skus.Models[b];` – Robin Zigmond May 25 '20 at 11:58
  • @RobinZigmond I agree with you – Shubham Khatri May 25 '20 at 12:15