I have an object that looks like this
{
"AF" : {
"name" : "Afghanistan"
},
"AL" : {
"name" : "Albania"
}
}
It has objects for all countries.
What I would like to do is copy the objects from certain ISO’s and add them to the top of the object (without removing the original).
What I started to do is this:
var filtered = _.collect(data, function(item, key){
if($.inArray(item.iso, ['US','CA']) !== -1) {
return item;
}
});
This gives me an array, with the objects. But, how would I add these to the original object?
Thank you!
As @mu-is-too-short said, JS objects have no mandatory ordering of their properties.
Also, your objects’ properties don’t have an
isoproperty, which you’re depending upon.Please edit your question once you’ve seen that 🙂
If your code is depending on that, you’re going the wrong way. As he suggests, you should use an array instead, but you can keep the objects inside of it. I’ll suppose you start with a structure of the object literal shown first in your question. With this snippet, you’ll be creating an array with the default order, and then adding the filtered objects to the head of that array: