简体   繁体   English

以对象作为键值对中的值构建数组

[英]Build Array with Objects as the value in key value pairs

I've been absolutely grinding my gears on this and I'm trying to figure out how to build the following data structure in Javascript:我一直在磨我的齿轮,我试图弄清楚如何在 Javascript 中构建以下数据结构:

[arrayValue: {objectKey: objectValue}, arrayValue2: {objectKey: objectValue}]

I've tried the following:我尝试了以下方法:

var arr = [];
var obj = {};

var name = "Test";
var password = 'password';
var value = 'value'

obj[name] = {name: name, value: value, password: password};

arr.push(obj);

Ther reason I'm building it this way with pushing data to the array is because I actually have a data set I'm looping through to iterate this multiple times.我以这种方式将数据推送到数组的原因是因为我实际上有一个数据集,我正在循环遍历它多次。

Unfortuantely, this gets me these results:不幸的是,这让我得到了这些结果:

[{"Test":{"name":"Test","value":"value","password":"password"}}, {"Test2":{"name":"Test","value":"value","password":"password"}}]

I am intending to build this as follows:我打算按如下方式构建它:

["Test":{"name":"Test","value":"value","password":"password"}, "Test2":{"name":"Test","value":"value","password":"password"}]

The reason for this, is I need to be able to target the array objects by name like arr[Test].name instead of arr[0].name这样做的原因是我需要能够通过名称来定位数组对象,例如arr[Test].name而不是arr[0].name

Thanks so much for any help on this.非常感谢您对此的任何帮助。

Arrays cannot have named objects, so you are not able to access part of an array with array['Test'] syntax. Arrays 不能有命名对象,因此您无法使用array['Test']语法访问数组的一部分。 Objects in an array can only have indices (indexes) so if you want to put an object in an array, you will need to access it by index.数组中的对象只能有索引(索引),所以如果你想把一个 object 放在一个数组中,你需要通过索引来访问它。 The syntax of your intended build is invalid.您预期构建的语法无效。

But with that said, if you don't intend to iterate over the array but instead just want to access certain items by their name, why don't you just put each object inside of a "container" object?但是话虽如此,如果您不打算遍历数组而只想按名称访问某些项目,为什么不将每个 object 放在“容器”object 中?

Arrays can't have specific keys. Arrays 不能有特定的键。 They are only indexed by numbers.它们仅按数字索引。 You can use arr[variable].name on objects您可以在对象上使用arr[variable].name

 var obj = {One: 1, Two: 2, Three: 3} var num = "Three" console.log(obj[num]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM