JS在js或部分解构上解构一些变量而不是其他变量

时间:2017-08-02 15:36:35

标签: javascript typescript ecmascript-6

是否可以仅对我需要的值进行解构而不是全部:

 let {myVar, _ , lastVar} = {first:"I need this", second: "Not this", third:"I also need this"}

3 个答案:

答案 0 :(得分:2)

当然可以。

如果您有一个对象,例如:{foo: 4, bar: 2},则只需要foo

let { foo } = {foo: 4, bar: 2};

这也有效:

let {first: first, third: third} = {first:"I need this", second: "Not this", third:"I also need this"}

答案 1 :(得分:1)

是,

let { a } = { a: 'a', b: 'b', c: 'c' }
// a is 'a'

let { a, ...rest } = {a: 'a', b: 'b'., c: 'c' }
// a is 'a'
// rest is { b: 'b', c: 'c' }

[编辑 - 使用您的值]

let {first, third} = {first:"I need this", second: "Not this", third:"I also need this"}
// if you really want to change the variable names
let myVar = first, lastVar = third

答案 2 :(得分:0)

您可以轻松地重命名非结构化字段:

const o = {
  first:"I need this", 
  second: "Not this", 
  third:"I also need this"};

const {first: myVar, third: lastVar, ...rest} = o;

// 
console.log(`  myVar - ${myVar}`);
console.log(`lastVar - ${lastVar}`);
console.log(`   rest - ${JSON.stringify(rest)}`);