如何比较和计算放置在数组中的javascript几个对象“属性值的实例? [英] How to compare and count instances of several objects' property values placed in array in javascript?

查看:94
本文介绍了如何比较和计算放置在数组中的javascript几个对象“属性值的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图计算放在array.I几个对象的属性值的实例是在寻找一种方法来有效地遍历这些值的阶段。
阵列的结构可能如下所示:

I've been trying to count property value instances of several objects placed in array.I am on the stage of finding a way to effectively iterate over these values. The structure of array may look as follows:

var arr=[{1:["option1","option2"],2:["option2"],3:["option1"]},{1:["option2","option1"],2:["option1"],3:["option1"]}]

阵列可能含有未知数量的对象。每个对象的属性可能含有未知号码放入数组的值。每个对象都具有相同的属性,所以我只是试图合并所有对象的第一个对象的属性。我相信,它看起来笨拙和可读性很差,但它是我迄今为止发现的唯一途径。它几乎工作,但我相信行为可能是未predictable。

Array may contain unknown number of objects. Each object property may contain unknown number of values put into array. Each object has same properties, so I simply tried to merge all objects properties with the first object. As I believe, it looks clumsy and poorly readable, but it's the only way I found so far. It almost works, but I believe the behaviour may be unpredictable.

for(var firstobj=0,val=0,i=1,prop=1;arr.length>i;prop++,val++)
{
 if(prop>Object.getOwnPropertyNames(arr[i]).length)
{
    i++;
    prop=1;
}
else if(prop<Object.getOwnPropertyNames(arr[i]).length)
{
    i+0;
}
if(arr[i][prop].length<=val)
 {
  val=0;  
}
arr[firstobj][prop].push(arr[i][prop][val]);
}

正如你所见,我尝试移动到下一个数组指数(I)操纵循环,只有当对象的属性[道具]到达终点,并试图通过拖欠VAL为0,以控制内部数组迭代,如果增长速度比磁盘阵列的大长度。不过,我并不满足于此code。可能是你可以建议其他任何解决问题的方法。怎样才能更好地我prepare多个对象值为了以后算自己为每个属性OCCURENCES?谢谢你。

As you see, I try to manipulate iteration by moving to next array index (i) only when object's properties [prop] reach the end and try to control internal array iteration by defaulting val to 0, if it grows larger than array's length. However, I am not satisfied with this code. May be you can suggest any other solutions to the problem. How can I better prepare multiple object values in order to later count their occurences for each property? Thanks.

推荐答案

使用嵌套循环处理数组或对象的每个层面。

Use nested loops to process each level of array or object.

for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) { // skip properties inherited from prototype
            var arr2 = obj[key];
            for (var j = 0; j < arr2.length; j++) {
                // Do something with arr2[j]
            }
        }
    }
}

这篇关于如何比较和计算放置在数组中的javascript几个对象“属性值的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆