Reputation: 23544
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!
Upvotes: 1
Views: 728
Reputation: 2579
As @mu-is-too-short said, JS objects have no mandatory ordering of their properties.
Also, your objects' properties don't have an iso
property, 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:
var data = {
"AF" : {
"name" : "Afghanistan"
},
"AL" : {
"name" : "Albania"
}
};
var countries = _.collect(data, _.identity);
var repeated = [];
_.forEach(countries, function(country) {
if (repeatsAtTheTop(country)) {
// Added in reverse order so it preserves the
// original once unshifted into the original array
repeated.unshift(country);
}
});
_.forEach(repeated, function(item, index) { countries.unshift(item) });
Upvotes: 1