0

I have the following object:

{
  "EekvB3cnwEzE":{
     "name":"hi",
  },
  "Brv1R4C6bZnD":{
     "name":"yup",
  },
  "kRwRXju6ALJZ":{
     "name":"okay",
  }
}

I am trying to add each of these items into an array. I do the following code but for some reason, I get back [] in my console.log

Could anyone help me figure out what's wrong?

$scope.items = [];

$http.get("/url").success(function(data) {
    $.each(data, function(key, value) { $scope.items[key] = value; });
    console.log($scope.items);
});

2 Answers 2

4

Named keys will be ignored when you log an array.

If you want them to show up there, you'll need to replace key (in this bit of code $scope.items[key]) with a number or use a .push(value) instead of an assignment.

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

4 Comments

I'd like to have my array index still be the "key" because I want to be able to search for them by key. is there no way to do this in javascript?
@bryan An "array" with named indexes is an object, which you already have in the first place.
@bryan — The point of an array is to have an ordered list of things. That order is described by the property names, which are numbers. If you want named keys, use a plain object (like the thing you appear to be copying the values from) instead of an array.
Ah okay, that makes sense. Thank you both for clarifying.
0

There must be something wrong with your ajax call. Because the following works:

var x = [];
$.each({
  "EekvB3cnwEzE":{
     "name":"hi",
  },
  "Brv1R4C6bZnD":{
     "name":"yup",
  },
  "kRwRXju6ALJZ":{
     "name":"okay",
  }
}, function(key, value){
    x[key] = value;
});
console.log(x);

It will log:

[EekvB3cnwEzE: Object, Brv1R4C6bZnD: Object, kRwRXju6ALJZ: Object]

1 Comment

When I do console.log(key, value); I get back each item in the JSON. So I don't think there is anything wrong with my ajax call.

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.