How do I slice an array from an array of object literals?

雨燕双飞 提交于 2019-12-05 10:40:34
var getCountry = function (country) {
    var out = [];
    for (var i = 0, len = arr.length; i < len; i++)
        if (arr[i].country === country) out.push(arr[i]);
    return out;
};

Demo: http://jsfiddle.net/YwytD/1/

"I want to create a new array containing only those objects where the property country is "United States""

This is exactly what the Array.filter() method is for:

var filteredArray = arr.filter(function(val, i, a) {
                                  return val.country==="United States";
                    });

Note that the .filter() method isn't available in IE before version 9, but the MDN page I linked to above shows you exactly how to implement it so reading that page should in itself answer your question.

Note also that in the (non-working) code in the question, your two for loops are basically doing the same thing as each other because they're both iterating over arr, so it doesn't make sense to nest them like that. You shouldn't use a for..in loop on an array, but if you do the key values will be the numeric indexes, it doesn't somehow pick up the properties of the object stored at each index.

EDIT:

"Some of the object literals have the same value for a given property, and I want to create a new array containing only those object literals."

OK, re-reading this I guess you didn't really want to select elements by specifying a country, you wanted to select elements for any country that had duplicate entries? So if there were another three elements that all had "New Zealand" you'd want to select them in addition to the "United States" ones? If so, you could do something like this:

var countryCount = {},
    i;
for (i = 0; i < arr.length; i++)
    if (countryCount.hasOwnProperty(arr[i].country)
       countryCount[arr[i].country]++;
    else
       countryCount[arr[i].country] = 1;

var filteredArr = arr.filter(function(val, i, a) {
                      return countryCount[val.country] > 1;
                  });

There is a simpler way of doing this, I think this is what you want var new_arr = arr.filter(function(obj){ return obj['country'] === 'United States'; }) This will filter your results into new_arr Of course you can make it better and more generic than just 'United States'

Edit: Whoops, got your question just now

Answer: Nested Filters :)

function getKeyStuff(key) {
    return arr.filter( function(obj) { 
        var new_arr = arr.filter( function(inner_obj) { 
            return inner_obj[key] === obj[key]; 
        });
        return new_arr.length > 1; 
    });
}

Here is my solution:

// assuming arr is already set

var num_obj = arr.length;
var obj_by_country = {}, obj;
for (var i = 0; i < num_obj; i++) {
  obj = arr[i];
  if (!obj_by_country[obj.country]) {
    obj_by_country[obj.country] = [];
  }
  obj_by_country[obj.country].push(obj);
}

// build final array
var final_array = [];
for (i in obj_by_country) {
  if (obj_by_country[i].length > 1) {
    final_array.push(obj_by_country[i]);
  }
}

Can you use JQuery?

var arr = [];
arr[0] = { country: "United States", num: 27 };
arr[1] = { country: "Australia", num: 5 };
arr[2] = { country: "United States", num: 7 };

var newArray = [];
$.each(arr, function(){
   if(this.country == "United States")
      newArray.push(this);
});
getByKey = function(arr, key, value) {
    var results = [];
    for(var i = 0; i < arr.length; i++) {
       if(arr[i][key] === value) {
           results.push(arr[i]);
       }
    }
    return results
}

here's a working example http://jsfiddle.net/michaelghayes/UyHYz/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!