1

Please refer to fiddle js file object obj1. (I'm starting out with an object this format because it represents what I get back from Ajax when PHP echos back an ordered key,value PHP array).

var obj1 = {
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
};

box1.innerText = "Object: " + JSON.stringify(obj1);

var arr1 = [];

for( keystr in obj1 ) {
    box2.innerText = keystr;
    valstr = obj1[keystr];
    arr1.push({keystr : valstr});
}

box3.innerText = "Array: " + JSON.stringify(arr1);

For those who ask why I'm trying to do this: Because I want to see if I can preserve the order (I have heard js objects are not ordered?) and because it happens to be the format needed for the function argument I'm going to pass the data to next.

As you can see what is happening, the identifier (i.e. "keystr") is getting used for the key, instead of the string itself (i.e. "key1", "key2", "key3").

What approach is recommended here? Thanks!

Mark Seagoe
  • 480
  • 8
  • 15
  • Possible duplicate of [Variable as the property name in a JavaScript object literal?](https://stackoverflow.com/questions/11043026/variable-as-the-property-name-in-a-javascript-object-literal) – t.niese Jan 10 '18 at 04:39
  • Since es6 you can write `arr1.push({[keystr] : valstr})`. – t.niese Jan 10 '18 at 04:41

1 Answers1

2

Yes, when you define an object literal that way the specified key is used as it is. You can use bracket notation which uses the value of the identifier.

var obj = {};
obj[keystr] = obj1[keystr];
arr1.push(obj);

Note that some browsers like Chrome are known to order the object's properties by key, but it's an implementation-specific feature and you shouldn't rely on it. Order of JavaScript object's properties is undefined.

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Yippee! Thanks for the very fast and correct solution! I replaced what I had in the for loop, and it just works! – Mark Seagoe May 30 '15 at 02:37
  • @SedesGobhani You are welcome. By using bracket notation the _value_ of the identifier is used for setting the property name but using object literal syntax, the _name_ of the identifier is used as the property's name. – Ram May 30 '15 at 02:57