Best way to store a key=>value array in JavaScript? - 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;
});

Related

Assigning K,V pairs to a JSON object in NodeJS

I have a NodeJS script that takes data from a source in the form of "key, value" pairs, and I would like to put that data into a JSON object.
I am using SNMP to get the k, v pairs, where the key is the OID. I would like to then map those values onto a JSON object without having to iteratively check each OID against a known value.
The k,v pairs are stored in objects as such, and I have no flexibility over this incoming data.
let pair = {
key: "abc...",
value: "xyz..."
}
I have defined the JSON object as an empty structure.
let jsonObject = {
ipaddress: "",
network: {
uptime: "",
throughput: "",
devices: ""
}
}
And I iterate through my keys (pairs is the name of an array containing the k,v objects)
for (let i = 0; i < pairs.length; i++) {
if (pairs[i].key == "1.2.3.4.5.6.7") jsonObject.ipaddress = pairs[i].value;
if (pairs[i].key == "2.3.4.5.6.7.8") jsonObject.network.uptime = pairs[i].value;
if (pairs[i].key == "3.4.5.6.7.8.9") jsonObject.network.devices = pairs[i].value;
}
I would like to know if there is any way to simplify this, as I have around 200 keys to process (the above code is simply an example), and it doesn't seem particularly well optimised for me to iterate over every possible key.
EDIT: The jsonObject is a lot more complex than shown here, with lots of layers and the names of the keys do not match up 1:1 with the json object property names as shown.
EDIT 2: This seems like an odd situation, I know.
For example, I want to take the K,V input:
Key Value
1.2.3.4.5.6 "10.0.0.1"
2.3.4.5.6.7 "3 Days 14 Hours 32 Minutes"
3.4.5.6.7.8 "1.1.1.1"
And convert it to a dissimilarly named JSON object
{
uptime: "3 Days 14 Hours 32 Minutes",
networking: {
ip: "10.0.0.1",
dns: "1.1.1.1"
}
}
Potentially using some form of mapping, instead of using ~200 if statements
Use the Array.prototype.reduce function.
const { name, ...properties } = pairs.reduce(
(obj, { key, value }) => Object.assign(obj, { [key]: value }),
{}
)
const obj = { name, properties }
Reduce will reduce an array into a scalar, in this case an object with all k,v pairs as fields with values on an object, starting with {} as a default value the merging each k,v pair 1 at a time.
Object.assign will merge objects, overwriting objects on the left with the fields of keys of objects on the right.
And finally the syntax to dynamically add a key on an object literal is { [k]: v }
By the way this is a useful trick for reducing the complexity of algorithms where you need to look up values in an array in a loop. Simply create an index of one array then in the loop, lookup in the index instead.
You can use Array.prototype.forEach for iterating and assigning the object.
const jsonObject = {
name: '',
properties: {
email: '',
address: '',
town: ''
}
};
const pairs = [{key: 'name', value: 'thatsimplekid'},
{key: 'email', value: 'aaa#domain.com'},
{key: 'town', value: 'myTown'},
{key: 'address', value:'123 main st' }];
pairs.forEach( ({key, value}) =>
jsonObject.hasOwnProperty(key) ?
jsonObject[key] = value :
jsonObject.properties[key] = value);
console.log(jsonObject);
for (let i = 0; i < pairs.length; i++) {
const key = pairs[i].key;
const value = pairs[i].value;
if (pairs[i].key == "name") {
jsonObject[key] = value;
} else {
jsonObject.properties[key] = value;
}
}
After the 'name' all values goes to the properties object, so a simple if would do it

Javascript multidimensional associated array error [duplicate]

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);

Sort javascript key/value pairs inside object

I have some problem with sorting items inside object. So I have something like this:
var someObject = {
'type1': 'abc',
'type2': 'gty',
'type3': 'qwe',
'type4': 'bbvdd',
'type5': 'zxczvdf'
};
I want to sort someObject by value, and this is where I have problem.
I have sorting function that should return key/value pairs sorted by value:
function SortObject(passedObject) {
var values = [];
var sorted_obj = {};
for (var key in passedObject) {
if (passedObject.hasOwnProperty(key)) {
values.push(passedObject[key]);
}
}
// sort keys
values.sort();
// create new object based on Sorted Keys
jQuery.each(values, function (i, value) {
var key = GetKey(passedObject, value);
sorted_obj[key] = value;
});
return sorted_obj;
}
and function to get key:
function GetKey(someObject, value) {
for (var key in someObject) {
if (someObject[key] === value) {
return key;
}
}
}
The problem is in last part when creating new, returning object - it's sorted by key again. Why? And this is specific situation when i have to operate on object NOT on array (yes I know that would be easier...)
Does anyone know how to sort items in object?
Plain objects don't have order at all. Arrays -that are a special types of objects- have.
The most close thing that you can have is an array with the object values sorted . Something like, for example:
_valuesOfAnObjectSorted = Object.keys(object).map(function(k){ return object[k]; }).sort();
You have two possibilities:
Refactor your object into an array
Something like this:
var myObj = [
['type1', 'abc'],
['type2', 'gty'],
...
];
Or even better, since using it somewhere would not rely on array positions but full named keys:
var myObj = [
{name: 'type1', val:'abc'},
{name: 'type2', val:'gty'},
...
];
Use your object with an auxiliar array
Wherever you want to use your object ordered by the keys, you can extract the keys as an array, order it and traverse it to access the object
var ordKeys = Object.keys(myObj).sort(); // pass inside a function if you want specific order
var key;
for (var i = 0, len = ordKeys.length; i < len; i +=1) {
key = ordKeys[i]
alert(key + " - " + myObj[key]);
}
Combination of both of them
If the object is not constructed by you, but comes from somewhere else, you can use the second option approach to construct an array of objects as in the first option. That would let you use your array anywhere with perfect order.
EDIT
You might want to check the library underscore.js. There you have extremely useful methods that could do the trick pretty easily. Probably the method _.pairs with some mapping would do all the work in one statement.

Converting an object literal to a sorted Array

I have an object literal, where the values of its key are more objects, and one of the keys of the inner objects is named "rank" - and has an floating point value. I want to convert the object literal to an array of the inner objects, sorted by the value of "rank".
Input Object:
{
452:{
bla:123,
dff:233,
rank:2
},
234:{
bla:123,
dff:233,
rank:1
}
}
Output Array:
[
{ bla:123, dff:233, rank:1},
{ bla:123, dff:233, rank:2 }
]
Example:
var data = {
foo: {
rank: 5
},
bar: {
rank: 2
},
baz: {
rank: 8
}
};
Javascript:
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
That would first sort the inner objects by the value of obj.rank and after that map the containing objects into an Array.
Result: [{rank: 2}, {rank: 5}, {rank: 8}]
Reference: Object.keys, Array.prototype.sort, Array.prototype.map
The above code contains ECMAscript 262 edition 5 code, which is available in all modern browsers. If you want to support legacy browsers as well, you need to include one of the various ES5-Shim libraries.
Iterate over your object's properties, pushing the inner objects into an array, and then sort the array with a custom sort function:
var inputObject = {}, // your object here
arr = [];
for (var k in inputObject)
arr.push(inputObject[k]);
arr.sort(function(a,b) { return a.rank - b.rank; });

Javascript data structure for fast lookup and ordered looping?

is there a data structure or a pattern in Javascript that can be used for both fast lookup (by key, as with associative arrays) and for ordered looping?
Right, now I am using object literals to store my data but I just disovered that Chrome does not maintain the order when looping over the property names.
Is there a common way to solve this in Javascript?
Thanks for any hints.
Create a data structure yourselves. Store the ordering in an array that is internal to the structure. Store the objects mapped by a key in a regular object. Let's call it OrderedMap which will have a map, an array, and four basic methods.
OrderedMap
map
_array
set(key, value)
get(key)
remove(key)
forEach(fn)
function OrderedMap() {
this.map = {};
this._array = [];
}
When inserting an element, add it to the array at the desired position as well as to the object. Insertion by index or at the end is in O(1).
OrderedMap.prototype.set = function(key, value) {
// key already exists, replace value
if(key in this.map) {
this.map[key] = value;
}
// insert new key and value
else {
this._array.push(key);
this.map[key] = value;
}
};
When deleting an object, remove it from the array and the object. If deleting by a key or a value, complexity is O(n) since you will need to traverse the internal array that maintains ordering. When deleting by index, complexity is O(1) since you have direct access to the value in both the array and the object.
OrderedMap.prototype.remove = function(key) {
var index = this._array.indexOf(key);
if(index == -1) {
throw new Error('key does not exist');
}
this._array.splice(index, 1);
delete this.map[key];
};
Lookups will be in O(1). Retrieve the value by key from the associative array (object).
OrderedMap.prototype.get = function(key) {
return this.map[key];
};
Traversal will be ordered and can use either of the approaches. When ordered traversal is required, create an array with the objects (values only) and return it. Being an array, it would not support keyed access. The other option is to ask the client to provide a callback function that should be applied to each object in the array.
OrderedMap.prototype.forEach = function(f) {
var key, value;
for(var i = 0; i < this._array.length; i++) {
key = this._array[i];
value = this.map[key];
f(key, value);
}
};
See Google's implementation of a LinkedMap from the Closure Library for documentation and source for such a class.
The only instance in which Chrome doesn't maintain the order of keys in an object literal seems to be if the keys are numeric.
var properties = ["damsonplum", "9", "banana", "1", "apple", "cherry", "342"];
var objLiteral = {
damsonplum: new Date(),
"9": "nine",
banana: [1,2,3],
"1": "one",
apple: /.*/,
cherry: {a: 3, b: true},
"342": "three hundred forty-two"
}
function load() {
var literalKeyOrder = [];
for (var key in objLiteral) {
literalKeyOrder.push(key);
}
var incremental = {};
for (var i = 0, prop; prop = properties[i]; i++) {
incremental[prop] = objLiteral[prop];
}
var incrementalKeyOrder = [];
for (var key in incremental) {
incrementalKeyOrder.push(key);
}
alert("Expected order: " + properties.join() +
"\nKey order (literal): " + literalKeyOrder.join() +
"\nKey order (incremental): " + incrementalKeyOrder.join());
}
In Chrome, the above produces: "1,9,342,damsonplum,banana,apple,cherry".
In other browsers, it produces "damsonplum,9,banana,1,apple,cherry,342".
So unless your keys are numeric, I think even in Chrome, you're safe. And if your keys are numeric, maybe just prepend them with a string.
As
has been noted, if your keys are numeric
you can prepend them with a string to preserve order.
var qy = {
_141: '256k AAC',
_22: '720p H.264 192k AAC',
_84: '720p 3D 192k AAC',
_140: '128k AAC'
};
Example

Categories

Resources