Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Let's say I have an object that looks like this: {"1": "2", "3": "4"}

I don't have direct access to this data, so when I bring it in via ajax how can I convert it to an array? Like so: [{"1": "2"}, {"3": "4"}]

PS: I'm using this output data in an angular-ui typeahead which dislikes objects and only likes strings.

share|improve this question
    
So you want to turn an object into an array of objects with each element representing a property?' –  sma Sep 24 '14 at 17:14
    
Yes, that sounds about right –  matenji Sep 24 '14 at 17:16

1 Answer 1

up vote 2 down vote accepted

Here's a snippet:

var inputObj = {'1': '2', '3': '4'};
var output = [];
for (var key in inputObj) {
  // must create a temp object to set the key using a variable
  var tempObj = {};
  tempObj[key] = inputObj[key];
  output.push(tempObj);
}

console.log(output);

Hope that helps!

share|improve this answer
    
What does the [key] refer to? –  matenji Sep 24 '14 at 17:36
    
When you use a for loop to iterate over an object, it actually iterates over the keys (as in key/value pairs) of the object as the index. You can then use the key to get the value from the object using the index notation myObject[key]. For example, for an object {'myKey': 'myValue'}, you can get the key from the object via myObject['myKey']. Does that make sense? –  SteveD Sep 24 '14 at 17:47
    
@matenji: I made a slight typo in that comment -- I meant: For example, for an object {'myKey': 'myValue'}, you can get the value from the object via myObject['myKey']. –  SteveD Sep 24 '14 at 18:40
    
I get it, so what if you just want the value of myValue? –  matenji Sep 24 '14 at 18:41
    
@matenji: In this example, the value of the object is "myValue", so you would get it by using myObject['myKey']. That example is a little confusing because the values look like variable names. Here's a less confusing example: var employee = {'firstName': 'Steve', 'lastName': 'Davis'}; console.log('First name is: ' + employee['firstName']); That would print "First name is Steve". –  SteveD Sep 24 '14 at 18:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.