3

Given this:

var metadata = {
    title: 'Scratchpad',
    translations: [
       {
        title: 'JavaScript-Umgebung'
       }
    ]
};

const output = ({
  title: englishTitle,
  translations: [{
    title: localeTitle
  }]
}) => (
    console.log(englishTitle), // "Scratchpad"
    console.log(localeTitle)  // "JavaScript-Umgebung"
)

output(metadata);

Now translations is undefined:

console.log(JSON.stringify(translations))  // ❌ "undefined"

Question: Is there a way to create a variable translations within the params destructure expressions (e.g. within the function param parenthesis)

Ashley Coolman
  • 11,095
  • 5
  • 59
  • 81

1 Answers1

5

You can destructure translations as well as it's inner members:

var metadata = {
    title: 'Scratchpad',
    translations: [
       {
        title: 'JavaScript-Umgebung'
       }
    ]
};


const output = ({
  title: englishTitle,
  translations, // get translations
  translations: [{
    title: localeTitle
  }]
}) => (
    console.log(englishTitle), // "Scratchpad"
    console.log(localeTitle),  // "JavaScript-Umgebung"
    console.log(translations)  // [{ title: 'JavaScript-Umgebung' }]
)

output(metadata);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209