简体   繁体   中英

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:

[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

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. 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. 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?

Arrays can't have specific keys. They are only indexed by numbers. You can use arr[variable].name on objects

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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