Javascript:具有数组值的键

时间:2019-06-24 22:19:14

标签: javascript arrays typescript object ecmascript-6

我试图用键作为数字和值作为对象数组来制作一个对象。如何在javascript中完成此操作?

我想创建一个看起来像这样的对象:

{Key: "1", value: [Object, Object, ...], key: "2", value: [Object, Object, ...], key:"N", value: [Object, Object, ...]}

这在javascript / typescript中怎么可能?

我尝试过:

let myObj = {};
myObj["1"] = myObj["1"].push(Object)

以上代码无效。

2 个答案:

答案 0 :(得分:2)

$ob1 [1] "A1" "A2" $ob2 [1] "A9" "A10" 返回数组的新长度-因此只需调用该函数(不对返回值进行任何操作),确保已首先初始化目标数组:

push

您还可以定义自定义类型:

let myObj = {};
myObj["1"] = myObj["1"] || [];
myObj["1"].push(Object);

答案 1 :(得分:1)

这是可能的,并且可以通过多种方式实现。例如,要使用TypeScript实现所需的功能,可以执行以下操作:

/* Define a type describing the structure of your desired object (optional)
 */    
type CustomType = { [key: number]: Array<any> };

/* Create your object based on type definition with numbers as keys and array
   of objects as values */
const yourObject: CustomType = {
  1 : [1,2,3],
  2 : ['a','b','c'],
  3 : [ new Object(), new Object() ]
};

在JavaScript中,可以通过省略键入来实现:

const yourObject = {
  1: [1, 2, 3],
  2: ['a', 'b', 'c'],
  3: [new Object(), new Object()]
};

console.log(yourObject);

/* Adding more letters to value at key 2 */
yourObject[2].push('d', 'e', 'f');

console.log(yourObject);

希望有帮助!