简体   繁体   English

选择 object 属性的简写 - 结合 ES6 `Object Deconstruction` 和 `Object Property Value` 简写

[英]Shorthand for picking object properties - combine ES6 `Object Deconstruction` with `Object Property Value` shorthand

Following code outputs {name: "Bob", surname: "Smith"} and it works fine.以下代码输出{name: "Bob", surname: "Smith"}并且工作正常。 I want to know can I make it shorter.我想知道我可以缩短它。

((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
    const {
        name, // (a) create variable from deconstructing
        surname,
    } = person;

    return {
        name, // (b) reuse variable as new object parameter name (and value)
        surname
    }
})();

Can I somehow merge object deconstruction to variables (a) with returning a new object with Object Property Value shorthand (b) ?我可以以某种方式将 object 解构合并到变量(a)并返回一个新的 object 和 Object 属性值简写(b)吗?

I use here shorthand but then its purpose is defeated by the need to manually re-use parameters.我在这里使用速记,但它的目的因需要手动重用参数而失败。 I want to mention the name or surname word in my function once not twice...我想在我的 function 中提及namesurname词一次而不是两次...

Destructure person in the function's declaration:在函数声明中解构person

 const result = (({ name, surname } = { name: 'Bob', surname: 'Smith', age: 22, }) => ({ name, // (b) reuse variable as new object parameter name (and value) surname }))(); console.log(result);

You can not mention it at all你根本不能提


((person = { name: 'Bob', surname: 'Smith', age: 22, }) => {
    const {age,...ans} = person;
   return ans
})()


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM