如何在对象内部使用解构分配

时间:2019-06-25 22:12:20

标签: javascript typescript ecmascript-6

是否可以在对象内部使用解构分配?

这有效

CREATE TEMP FUNCTION RADIANS(x FLOAT64) AS (
  ACOS(-1) * x / 180
);

SELECT RADIANS(37);  -- returns 0.6457718232379019

想要这样做

        const test = {a: 'hey', b: 'hello'}
        const {a,b} = test;
        const destruct = {
            a,
            b
        };

3 个答案:

答案 0 :(得分:2)

如果我正确理解,看来spread syntax非常适合您的需求。

传播语法“ ...”使您可以将键/值对从源对象(即test)“传播”到目标对象(即destruct):< / p>

const test = {
  a: 'hey',
  b: 'hello',
  c: 'goodbye'
}

const destruct = {
  // {a,b}: test <-- invalid syntax
  ...test // equivalent using the "spread" syntax
};

console.log(destruct)
 

另外,如果您想从源对象中选择键的子集并将其散布到目标对象中,则可以通过以下方法实现:

const test = {
  a: 'hey',
  b: 'hello',
  c: 'goodbye'
}

/* Spread subset of keys from source object to target object */
const welcomeOnly = {
  ...({ a, b } = test, { a, b })
}

console.log('exclude goodbye, show welcomes only:', welcomeOnly);

第二个示例通过使用我们想要的键子集(testa)将源对象(即b)破坏为一个对象。

在该表达式的范围内(即()之间的所有内容),这些键可以作为局部变量访问。我们利用这一点,并将它们传递给新对象(即{ a, b })。由于新对象是在,之后声明的,因此它将作为表达式的结果返回。

答案 1 :(得分:0)

如果您尝试获取属性的子集,则可以使用rest运算符

const test = {
  a: 'hey',
  b: 'hello',
  c: 'goodbye'
};

const { c, ...destruct } = test;

console.log(destruct);

这将c分配给const,剩余的属性分配给const析构函数。首先列出所有不需要的属性,然后用其余运算符捕获剩余的属性。

也可以使用数组。

const test = ['hey', 'hello', 'goodbye'];

const [ first, ...rest ] = test;

console.log(rest);

答案 2 :(得分:0)

您可以尝试像这样工作以破坏数组!

    let abc = {
      a: 'hello',
      b: 'hey',
      c: 'hi, there!'
    }


    let {a: x, b:y, c:z} = abc;

    console.log(x,y,z)  

// "hello"
   "hey"
   "hi, there!"
相关问题