简体   繁体   English

如何从对象文字数组中切片数组?

[英]How do I slice an array from an array of object literals?

I have this array, in which each index contains an object literal. 我有这个数组,其中每个索引包含一个对象文字。 All of the object literals have the same properties. 所有对象文字都具有相同的属性。 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. 一些对象文字对于给定的属性具有相同的值,我想创建一个包含那些对象文字的新数组。

My idea is to sort the array, and slice it into a new array... 我的想法是对数组进行排序,并将其切成新的数组...

Here is the array: 这是数组:

var arr = [];

arr[0] =
{
    country: "United States",
    num: 27
};

arr[1] =
{
    country: "Australia",
    num: 5
};

arr[2] =
{
    country: "United States",
    num: 7
};


So, I want to create a new array containing only those objects where the property country is "United States". 所以,我想创建一个新的数组,只包含属性country是“美国”的那些对象。 This is my crazy idea so far, which doesn't work: 到目前为止,这是我的疯狂想法,但这不起作用:

function getNewArray(arr)
{
    var arr2 = [];

    for(var key in arr)
    {
        for(var i = 0; i < arr.length - 1; i++)
        {
            if(arr.hasOwnProperty(key) && arr[i].name == arr[i + 1].name)
            {
                    arr2[i] = arr.slice(key);
            }
        }
    }

    return arr2;
}

var arr3 = getNewArray(arr).sort();

"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: 这正是Array.filter()方法的用途:

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. 请注意, .filter()方法在版本9之前的IE中不可用,但我上面链接的MDN页面向您显示了如何实现它,因此阅读该页面本身应该回答您的问题。

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. 还要注意,在问题中的(非工作)代码中,你的两个for循环基本上做了彼此相同的事情,因为它们都是在arr迭代,所以将它们嵌套起来是没有意义的。 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. 您不应该在数组上使用for..in循环,但如果您执行key将是数字索引,它不会以某种方式获取存储在每个索引处的对象的属性。

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' 有一种更简单的方法,我认为这就是你想要的var new_arr = arr.filter(function(obj){ return obj['country'] === 'United States'; })这会过滤你的结果进入new_arr当然,你可以使它变得更好,更通用而不仅仅是'美国'

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; 
    });
}
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/ 演示: http //jsfiddle.net/YwytD/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? 你能用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/ 这是一个工作示例http://jsfiddle.net/michaelghayes/UyHYz/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM