Javascript multidimensional associated array error [duplicate] - javascript

There is the following query results: (key1 and key2 could be any text)
id key1 key2 value
1 fred apple 2
2 mary orange 10
3 fred banana 7
4 fred orange 4
5 sarah melon 5
...
and I wish to store the data in a grid (maybe as an array) looping all the records like this:
apple orange banana melon
fred 2 4 7 -
mary - 10 - -
sarah - - - 5
In PHP this would be really easy, using associative arrays:
$result['fred']['apple'] = 2;
But in JavaScript associative arrays like this doesn't work.
After reading tons of tutorial, all I could get was this:
arr=[];
arr[1]['apple'] = 2;
but arr['fred']['apple'] = 2; doesn't work.
I tried arrays of objects, but objects properties can't be free text.
The more I was reading tutorials, the more I got confused...
Any idea is welcome :)

Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.
var obj = {};
obj['fred'] = {};
if('fred' in obj ){ } // can check for the presence of 'fred'
if(obj.fred) { } // also checks for presence of 'fred'
if(obj['fred']) { } // also checks for presence of 'fred'
// The following statements would all work
obj['fred']['apples'] = 1;
obj.fred.apples = 1;
obj['fred'].apples = 1;
// or build or initialize the structure outright
var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };
If you're looking over values, you might have something that looks like this:
var people = ['fred', 'alice'];
var fruit = ['apples', 'lemons'];
var grid = {};
for(var i = 0; i < people.length; i++){
var name = people[i];
if(name in grid == false){
grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors
}
for(var j = 0; j < fruit.length; j++){
var fruitName = fruit[j];
grid[name][fruitName] = 0;
}
}

If it doesn't have to be an array, you can create a "multidimensional" JS object...
<script type="text/javascript">
var myObj = {
fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 },
mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 },
sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 }
}
document.write(myObj['fred']['apples']);
</script>

Javascript is flexible:
var arr = {
"fred": {"apple": 2, "orange": 4},
"mary": {}
//etc, etc
};
alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
alert(key + ": " + arr.fred[key]);

As I needed get all elements in a nice way I encountered this SO subject "Traversing 2 dimensional associative array/object" - no matter the name for me, because functionality counts.
var imgs_pl = {
'offer': { 'img': 'wer-handwritter_03.png', 'left': 1, 'top': 2 },
'portfolio': { 'img': 'wer-handwritter_10.png', 'left': 1, 'top': 2 },
'special': { 'img': 'wer-handwritter_15.png', 'left': 1, 'top': 2 }
};
for (key in imgs_pl) {
console.log(key);
for (subkey in imgs_pl[key]) {
console.log(imgs_pl[key][subkey]);
}
}

It appears that for some applications, there is a far simpler approach to multi dimensional associative arrays in javascript.
Given that the internal representation of all arrays are actually as objects of objects, it has been shown that the access time for numerically indexed elements is actually the same as for associative (text) indexed elements.
the access time for first-level associative indexed elements does not rise as the number of actual elements increases.
Given this, there may be many cases where it is actually better to use a concatenated string approach to create the equivalence of a multidimensional elements. For example:
store['fruit']['apples']['granny']['price'] = 10
store['cereal']['natural']['oats']['quack'] = 20
goes to:
store['fruit.apples.granny.price'] = 10
store['cereal.natural.oats.quack'] = 20
Advantages include:
no need to initialize sub-objects or figure out how to best combine objects
single-level access time. objects within objects need N times the access time
can use Object.keys() to extract all dimension information and..
can use the function regex.test(string) and the array.map function on the keys to pull out exactly what you want.
no hierarchy in the dimensions.
the "dot" is arbitrary - using underscore actually makes regex easier
there are lots of scripts for "flattening" JSON into and out of this format as well
can use all of the other nice array processing functions on keylist

You don't need to necessarily use Objects, you can do it with normal multi-dimensional Arrays.
This is my solution without Objects:
// Javascript
const matrix = [];
matrix.key1 = [
'value1',
'value2',
];
matrix.key2 = [
'value3',
];
which in PHP is equivalent to:
// PHP
$matrix = [
"key1" => [
'value1',
'value2',
],
"key2" => [
'value3',
]
];

Get the value for an array of associative arrays's property when the property name is an integer:
Starting with an Associative Array where the property names are integers:
var categories = [
{"1":"Category 1"},
{"2":"Category 2"},
{"3":"Category 3"},
{"4":"Category 4"}
];
Push items to the array:
categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});
Loop through array and do something with the property value.
for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
var category = categories[i][categoryid];
// log progress to the console
console.log(categoryid + " : " + category);
// ... do something
}
}
Console output should look like this:
1 : Category 1
2 : Category 2
3 : Category 3
4 : Category 4
2300 : Category 2300
2301 : Category 2301
As you can see, you can get around the associative array limitation and have a property name be an integer.
NOTE: The associative array in my example is the json you would have if you serialized a Dictionary[] object.

Don't use an array, use an object.
var foo = new Object();

<script language="javascript">
// Set values to variable
var sectionName = "TestSection";
var fileMap = "fileMapData";
var fileId = "foobar";
var fileValue= "foobar.png";
var fileId2 = "barfoo";
var fileValue2= "barfoo.jpg";
// Create top-level image object
var images = {};
// Create second-level object in images object with
// the name of sectionName value
images[sectionName] = {};
// Create a third level object
var fileMapObj = {};
// Add the third level object to the second level object
images[sectionName][fileMap] = fileMapObj;
// Add forth level associate array key and value data
images[sectionName][fileMap][fileId] = fileValue;
images[sectionName][fileMap][fileId2] = fileValue2;
// All variables
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);
// All keys with dots
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);
// Mixed with a different final key
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);
// Mixed brackets and dots...
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);
// This will FAIL! variable names must be in brackets!
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);
// Produces: "Example 5 Value: undefined".
// This will NOT work either. Values must be quoted in brackets.
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);
// Throws and exception and stops execution with error: fileMapData is not defined
// We never get here because of the uncaught exception above...
alert ("The End!");
</script>

var myObj = [];
myObj['Base'] = [];
myObj['Base']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['Base']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1'] = [];
myObj['SC1']['Base.panel.panel_base'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'', AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
myObj['SC1']['Base.panel.panel_top'] = {ContextParent:'',ClassParent:'',NameParent:'',Context:'Base',Class:'panel',Name:'panel_base',Visible:'',ValueIst:'',ValueSoll:'',
Align:'',AlignFrom:'',AlignTo:'',Content:'',onClick:'',Style:'',content_ger_sie:'',content_ger_du:'',content_eng:'' };
console.log(myObj);
if ('Base' in myObj) {
console.log('Base found');
if ('Base.panel.panel_base' in myObj['Base']) {
console.log('Base.panel.panel_base found');
console.log('old value: ' + myObj['Base']['Base.panel.panel_base'].Context);
myObj['Base']['Base.panel.panel_base'] = 'new Value';
console.log('new value: ' + myObj['Base']['Base.panel.panel_base']);
}
}
Output:
Base found
Base.panel.panel_base found
old value: Base
new value: new Value
The array operation works. There is no problem.
Iteration:
Object.keys(myObj['Base']).forEach(function(key, index) {
var value = objcons['Base'][key];
}, myObj);

Related

Javascript is empty after filling with data

Javascript array is empty after filling with values
I tried this code:
var browserdata = new Array();
// Fill the array with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata); // This shows an empty array
It should show { "qqq" => "zzz", "zzz" => 1 }
Actual output is [] (empty array).
You need to use Object data type instead of Array. Using object structure, you can assign properties to it and corresponding value for that property to get the desired output as { "qqq" => "zzz", "zzz" => 1 }
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
You can also use the another approach, to assign the property at the time object is declared:
var browserdata = {
'qqq': 'zzz',
'rrr': 1
};
console.log(browserdata);
It will never return empty as there are data in the array, with your code it will return an output
[qqq: "zzz", rrr: 1]
If you want to get an output like { "qqq" => "zzz", "zzz" => 1 } , You should use objects .Objects are nothing but a grouping of data,
for example, consider a student array with different data sets.
here you could define individual data or data sets like
student['name'] = john ;
student['mark'] = 20;
OR
students =[{name : john , mark :20} ,{name : rick, mark :20} ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://javascript.info/array
If new Array() is called with a single argument which is a number, then it creates an array without items, but with the given length.
It’s rarely used, because square brackets [] are shorter. Also there’s a tricky feature with it lets see.
var arr = new Array(2); // will it create an array of [2] ?
console.log( arr[0] ); // undefined! no elements.
console.log( arr.length ); // length 2
var browserdata = new Array();
browserdata[0] = "zzz";
browserdata[1] = 1;
console.log(browserdata);
console.log(browserdata.length);
That solution works for me. Initializing with {} rather than [] or new Array() works. Thanks.
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
Only the positive integer keys of array object are displayed by default, but the rest of the properties can still be accessed and seen in the Google Chrome console.
var arr = []
arr[1] = 1
arr[-1] = -1
arr[.1] = .1
arr.a = 'a'
arr['b'] = 'b'
console.log( arr ) // [undefined, 1]
console.log( arr.b ) // "b"
console.log( { ...arr } ) // { "1": 1, "-1": -1, "0.1": 0.1, "a": "a", "b": "b" }

Searching array with multiple keys

I can see this works fine for searching a simple array:
var arr1 = ['a','b','c','d','e'];
var index1 = arr1.indexOf('d');
console.log("index1:" + index1); // index1:3
When I try to do the same thing for a different kind of array, it doesn't find the "jane" value:
var arr2 = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
var index2 = arr2.indexOf('jane');
console.log("index2:" + index2); // index2:-1
Sorry - I realise I am probably missing something obvious. I have searched on SO / google for searching multi dimensional arrays, but I don't even know if the array in the 2nd example is a 2d / multi dimensional array, so I am probably not searching for the right thing.
You can use findIndex() method to find index of object with specific value.
var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
var index = arr.findIndex(e => e.name == 'jane')
console.log("index: " + index);
First of all: it's not a multi-dimensional array. It's an array consisting of objects. It's one-dimensional. To find an object you need to iterate through an array and check the needed key, e.g.:
arr.findIndex(function(el) { return el.name === 'jane' })
You could check all values of the objects and use Array#findIndex instead of Array#indexOf.
var arr2 = [{ id: 0, name: "petty" }, { id: 1, name: "jane" }, { id: 2, name: "with" }],
index2 = arr2.findIndex(o => Object.values(o).some(v => v === 'jane'));
console.log(index2);
var arr = [{"id":0,"name":"petty"},{"id":1,"name":"jane"},{"id":2,"name":"with"}];
arr.findIndex((item)=>{return item.name=="petty"})
//output is 0

How to sort object values in JavaScript when keys are numbers?

let's say I have such weird code:
var weirdo = {};
var ids = [10, 30, 11, 1, 4, 2];
var producers = ['Ford','Rover','BMW','Fiat','Renault','Mitsubishi'];
var n = producers.length;
for(var i=0; i<n; i++) {
weirdo[ids[i]] = producers[i];
}
// unknown code ???
How to sort weirdo by values? It's not array and no, I can't sort producers before filling weirdo.
Any ideas?
Oh, and relation id <=> producer is VERY IMPORANT!
You can use an array of objects:
var items = [
{id:10, producer:'Ford'},
{id:30, producer:'Rover'},
{id:11, producer:'BMW'},
{id:1, producer:'Fiat'},
{id:4, producer:'Renault'},
{id:2, producer:'Mitsubishi'},
]
// or, starting from your two arrays:
var items = [];
for (var i=0; i<ids.length && i<producers.length; i++)
items[i] = {id:ids[i], producer:producers[i]};
Then you can sort that array by id:
items.sort(function(a, b){ return a.id-b.id; });
...and iterate it with a for-loop.
Another solution would be an iterator array, to loop over an id<->producer object (weirdo) in the correct order:
var weirdo = {"10":"Ford","30":"Rover",...};
var ids = Object.keys(weirdo); // if not already built somewhere
ids.sort(function(a,b){return a-b;}); // sort numeric
// loop:
for (var i=0; i<ids.length; i++) {
var id=ids[i], producer=weirdo[id];
...
}
The short answer is that objects are unordered by spec. The properties of an object are just that - properties. They are served as you request them, they are not items to be moved around within the object.
How an object is visualized upon inspection is entirely up to the agent performing the visualization. For instance, if you were to write the following in Chrome
console.log({ x: 1, a: 2 });
... it would display the parameters in alphabetical order. That is not something innate to the object, but simply a matter of chrome implementation.
If you would, instead, write the following in chrome
for(key in { x: 1, a: 2 }) console.log(key);
... it would log an x, followed by an a, i.e. showing the properties for the same object in the order that they were added.
You could of course make sure that you add the properties to your object in the alphabetical/numerical order of their respective property names, but that would be missing the point, as there is no guarantee that all implementations will preserve the order of adding either.
Have you tried using Array.Sort?
http://jsfiddle.net/gRoberts/mXwdN/
var weirdo = {};
var producers = ['Ford','Rover','BMW','Fiat','Renault','Mitsubishi'];
producers.sort();
console.log(producers);
producers.map(function(item, index) {
this[index] = item;
}, weirdo);
console.log(weirdo);
Edit: Due to question being updated whilst I was working on a solution, please find an updated version based on the updated question:
http://jsfiddle.net/gRoberts/mXwdN/1/
var weirdo = {};
var ids = [10, 30, 11, 1, 4, 2];
var producers = ['Ford','Rover','BMW','Fiat','Renault','Mitsubishi'];
ids.sort();
ids.map(function(item, index) {
weirdo[item] = producers[index];
}, weirdo);
console.log(weirdo);​
​

Creating an object similar to an array or extending the Array prototype

I'm trying to make something similar to an array.
I need to be able to "release" an Index (set its value to undefined) but I don't want to lose the Index.
The "released" Indexes should be re-used whenever a new item is put into the array.
I'd like to be able to do something like:
example = new MyArray();
a = example.leaseIndex(); // returns 0
example[a] = "example value";
b = example.leaseIndex(); // returns 1
example[b] = "another value";
example.releaseIndex(0);
c = example.leaseIndex(); // returns 0
example[c] = "yet another value";
In my example leaseIndex finds an available index or if none are available pushes a new item onto the array and returns the index of that item.
I want to do this so that the array doesn't just grow bigger over time needlessly.
I can't remove the "released" items as each item in the array contains a reference to another item in the same array.
I've had minor successes with functions and arrays outside of the main one to keep track of the available indexes and assign and release them, but ideally I'd like the functionality to be part of the main array.
Would I have to add my functions to the Array (or its prototype) or is there another way? As not all my arrays need this functionality.
Hope this makes sense :/
update
I am trying to store wiring loom layouts, which are essentially a net diagram (points and information as to how the points are connected).
The picture shows an example loom. It has 3 Connectors; Red (0) with 2 Lines, Yellow (1) with 3 Lines and Green (2) with 2 Lines.
One of the lines on the Red Connector is Spliced (allowing multiple Lines to connect to a Single Line, the blue square)
This is how that loom would be stored.
loom = {
points = [
{ self: 0, list: [ 2 ] },
{ self: 1, list: [ 7 ] },
{ self: 2, list: [ 0 ] },
{ self: 3, list: [ 7 ] },
{ self: 4, list: [ 6 ] },
{ self: 5, list: [ 7 ] },
{ self: 6, list: [ 4 ] },
{ self: 7, owner: 1, list: [ 1, 3, 5 ] }
],
connectors = [
[ 0, 1 ],
[ 2, 3, 4 ],
[ 5, 6 ]
]
}
the elements in the connectors array contain the indexes of points in the points array.
the list array inside each points object contains the index of its destination(s) which are points too.
Im trying to make functions to help make managing the indexes easier, just wanted to know if there is a way to extend the array, or make something similar that incorporates the functionality. Using static functions would be OK and is what I've been using. I just wanted to see if i could extend the array, or use something like one so I didnt need to use the static functions.
I would add the methods to the Array's prototype, like this:
Array.prototype.leaseIndex = function () {
for (var i = 0; i < this.length; i++) {
if(typeof this[i] === "undefined") {
return i;
}
}
return this.length;
};
Array.prototype.releaseIndex = function (index) {
delete this[index];
};
So, your code would look like this:
example = [];
a = example.leaseIndex(); // returns 0
example[a] = "example value";
b = example.leaseIndex(); // returns 1
example[b] = "another value";
example.releaseIndex(0);
c = example.leaseIndex(); // returns 0
example[c] = "yet another value";
I hope it helps.
Here is a simple implementation using some static functions (without needing to fuss with methods):
var hop = function(obj, prop){
return Object.prototype.hasOwnProperty.call(obj, prop);
};
var leaseIndex = function(arr, value){
var i;
for(i=0; i<arr.length; i++){
if(!hop(arr, i)){
break;
}
}
arr[i] = value;
return i;
};
var releaseIndex = function(arr, i){
delete arr[i];
};
Of course, I have no idea if this is what you really want, since my algorithm is potentially O(N) and I am not sure you need all this complication.

Best way to store a key=>value array in JavaScript?

What's the best way to store a key=>value array in javascript, and how can that be looped through?
The key of each element should be a tag, such as {id} or just id and the value should be the numerical value of the id.
It should either be the element of an existing javascript class, or be a global variable which could easily be referenced through the class.
jQuery can be used.
That's just what a JavaScript object is:
var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;
You can loop through it using for..in loop:
for (var key in myArray) {
console.log("key " + key + " has value " + myArray[key]);
}
See also: Working with objects (MDN).
In ECMAScript6 there is also Map (see the browser compatibility table there):
An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.
The keys of an Object are Strings and Symbols, where they can be any value for a Map.
You can get the size of a Map easily while you have to manually keep track of size for an Object.
If I understood you correctly:
var hash = {};
hash['bob'] = 123;
hash['joe'] = 456;
var sum = 0;
for (var name in hash) {
sum += hash[name];
}
alert(sum); // 579
You can use Map.
A new data structure introduced in JavaScript ES6.
Alternative to JavaScript Object for storing key/value pairs.
Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
Get value of the Map using key
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
Get size of the Map
console.log(map.size); // 2
Check key exists in Map
console.log(map.has('name')); // true
console.log(map.has('age')); // false
Get keys
console.log(map.keys()); // MapIterator { 'name', 'id' }
Get values
console.log(map.values()); // MapIterator { 'John', 11 }
Get elements of the Map
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
Print key value pairs
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
Print only keys of the Map
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
Print only values of the Map
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
In javascript a key value array is stored as an object. There are such things as arrays in javascript, but they are also somewhat considered objects still, check this guys answer - Why can I add named properties to an array as if it were an object?
Arrays are typically seen using square bracket syntax, and objects ("key=>value" arrays) using curly bracket syntax, though you can access and set object properties using square bracket syntax as Alexey Romanov has shown.
Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well.
Simple Array eg.
$(document).ready(function(){
var countries = ['Canada','Us','France','Italy'];
console.log('I am from '+countries[0]);
$.each(countries, function(key, value) {
console.log(key, value);
});
});
Output -
0 "Canada"
1 "Us"
2 "France"
3 "Italy"
We see above that we can loop a numerical array using the jQuery.each function and access info outside of the loop using square brackets with numerical keys.
Simple Object (json)
$(document).ready(function(){
var person = {
name: "James",
occupation: "programmer",
height: {
feet: 6,
inches: 1
},
}
console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation);
$.each(person, function(key, value) {
console.log(key, value);
});
});
Output -
My name is James and I am a 6 ft 1 programmer
name James
occupation programmer
height Object {feet: 6, inches: 1}
In a language like php this would be considered a multidimensional array with key value pairs, or an array within an array. I'm assuming because you asked about how to loop through a key value array you would want to know how to get an object (key=>value array) like the person object above to have, let's say, more than one person.
Well, now that we know javascript arrays are used typically for numeric indexing and objects more flexibly for associative indexing, we will use them together to create an array of objects that we can loop through, like so -
JSON array (array of objects) -
$(document).ready(function(){
var people = [
{
name: "James",
occupation: "programmer",
height: {
feet: 6,
inches: 1
}
}, {
name: "Peter",
occupation: "designer",
height: {
feet: 4,
inches: 10
}
}, {
name: "Joshua",
occupation: "CEO",
height: {
feet: 5,
inches: 11
}
}
];
console.log("My name is "+people[2].name+" and I am a "+people[2].height.feet+" ft "+people[2].height.inches+" "+people[2].occupation+"\n");
$.each(people, function(key, person) {
console.log("My name is "+person.name+" and I am a "+person.height.feet+" ft "+person.height.inches+" "+person.occupation+"\n");
});
});
Output -
My name is Joshua and I am a 5 ft 11 CEO
My name is James and I am a 6 ft 1 programmer
My name is Peter and I am a 4 ft 10 designer
My name is Joshua and I am a 5 ft 11 CEO
Note that outside the loop I have to use the square bracket syntax with a numeric key because this is now an numerically indexed array of objects, and of course inside the loop the numeric key is implied.
Objects inside an array:
var cars = [
{ "id": 1, brand: "Ferrari" }
, { "id": 2, brand: "Lotus" }
, { "id": 3, brand: "Lamborghini" }
];
Simply do this
var key = "keyOne";
var obj = {};
obj[key] = someValue;
I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too
var countries = ['Canada','Us','France','Italy'];
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

Categories

Resources