如何使用数字键名来构造对象?

时间:2018-06-11 16:38:07

标签: javascript object ecmascript-6

我有需要在组件中进行解构的道具。因为它来自API,它实际上是一个对象,我想从0到39获取对象。但是,当我尝试以这种方式对它们进行解构时:

 const { 0, ...39: weatherData } = this.props;

由于逗号,VSCode给出了意外令牌错误。如何在不必枚举每一个物体的情况下对道具进行构造?

2 个答案:

答案 0 :(得分:0)

您可以将一个数组作为对象的目标,该数组仅采用数字索引并将其切片为所需长度。



const array = Object
    .assign([], { abc: 1, 0: 100, 1: 101, 39: 139, 40: 140 })
    .slice(0, 40);

console.log(Array.isArray(array));
console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

在javascript中,即使您使用number作为键创建对象,键也始终为字符串,请使用以下示例:



const obj = {
  [1]: 1,
  anotherThing: 2
};

console.log(Object.keys(obj))




但是,由于'1'1是文字,因此无法在解构分配中使用它们,为了使用数字键,您必须将对象转换为iterable或手动映射属性,

将对象转换为可迭代的最简单方法是将Object.assign与数组一起使用,因为数组也是一个对象,您可以执行以下操作:

const arr = Object.assign([], obj);

为了实现你的目的,例如:



const obj = {
  [0]: 0,
  [1]: 1,
  wheaterData: 'wheaterData',
  anotherNonNumericProp: '1'
};

const arrOfNumericProps = Object.assign([], obj);

const [prop0, prop1] = arrOfNumericProps;

const {wheaterData,
  ...rest
} = arrOfNumericProps;

console.log(prop0);
console.log(prop1);

console.log(wheaterData);
console.log(rest);




相关问题