如何将所有中间属性变量保存在深层嵌套的结构中

时间:2017-12-07 07:00:20

标签: javascript ecmascript-6 babeljs

鉴于此:

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);

现在translations未定义:

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

问题:有没有办法在params destructure表达式中创建变量translations(例如在函数param括号内)

1 个答案:

答案 0 :(得分:4)

您可以解构翻译及其内部成员:

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);