使用ES6/7从具有与变量名称相同键的变量创建对象

create object from variables with keys as same as variables names with ES6/7

本文关键字:创建对象 变量 变量名 ES6 使用      更新时间:2023-09-26

我想从多个变量创建一个对象,但我不想逐一列出这些变量:

let [x, y, z] = [1, 2, 3];
let obj = ??? // something shorter than {x: x, y: y, z: z};
obj.x === 1; // i want true here
obj.y === 2; // i want true here
obj.z === 3; // i want true here

此外,我想从一个对象中剪切特殊值,并将它们放入另一个具有相同密钥的对象中:

let obj1 = {
  subobj1: {
    x: 1,
    y: 2,
    z: 3
  }
};
let obj2 = ??? // something shorter than {x: obj1.subobj1.x, y: obj1.subobj1.y,};
obj2.x === 1; // i want true here
obj2.y === 2; // i want true here
typeof obj2.z === "undefined"; // i want true here

如何使用ES6/7完成这些操作?

对于第一个,您可以使用这个

let [x, y, z] = [1, 2, 3];
let obj = { x, y, z };

我认为没有比这更短的方法来完成第二项任务了。