2

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.

3
  • So you want to turn an object into an array of objects with each element representing a property?' Commented Sep 24, 2014 at 17:14
  • Yes, that sounds about right Commented Sep 24, 2014 at 17:16
  • u can try this way $scope.arrayList = @Html.Raw(Json.Encode(Object)); Commented Jun 17, 2015 at 7:12

1 Answer 1

9

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!

Sign up to request clarification or add additional context in comments.

5 Comments

What does the [key] refer to?
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?
@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'].
I get it, so what if you just want the value of myValue?
@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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.