将JavaScript项目按一个属性分组 [英] Group javascript items by one property

查看:55
本文介绍了将JavaScript项目按一个属性分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与问题有关.您必须先阅读它.

My question is related to this question. You will have to first read it.

var ids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B22*B22";

现在,我有了一个javascript对象数组.我想基于CODE对我的对象进行分组.因此,该代码字符串中可能存在重复的代码.

Now that I have an array of javascript objects. I want to group my objects based on CODE. So there can be duplicate codes in that code string.

根据上面更改的字符串,我有Brain和Andy的相同代码.所以,现在我要两个数组.在一个对象中,只有一个对象仅包含John的详细信息,在另一个对象中,将包含两个对象包含Brain和Andy的详细信息.

As per the above changed strings, I have same code for Brain and Andy. So, now I want two arrays. In one there will be only one object containing details of only John and in the other object there will be two objects containing details of Brain and Andy.

举例来说,我已经吃了3件东西.实际上,可以有很多并且也可以有很多不同的代码集.

Just for example I've taken 3 items. In actual there can be many and also there can be many set of distinct codes.

更新
我需要一种类似于@Pointy内置的groupMap对象的结构.但是我将使用@patrick的代码来实现该结构.非常感谢他们俩.

UPDATE
I needed the structure like the one built in groupMap object by the @Pointy. But I will use @patrick's code to achieve that structure. Many thanks to both of them.

推荐答案

要说出所需的确切结果结构有些困难.

It is a little hard to tell the exact resulting structure that you want.

此代码:

       // Split values into arrays
Code = Code.split('*');
Name = Name.split('*');
ids = ids.split('*');

       // cache the length of one and create the result object
var length = Code.length;
var result = {};

       // Iterate over each array item
       // If we come across a new code, 
       //    add it to result with an empty array
for(var i = 0; i < length; i++) {
    if(Code[i] in result == false) {
        result[ Code[i] ] = [];
    }
            // Push a new object into the Code at "i" with the Name and ID at "i"
    result[ Code[i] ].push({ name:Name[i], id:ids[i] });
}

将产生以下结构:

// Resulting object
{
      // A12 has array with one object
    A12: [ {id: "1", name: "John"} ],

      // B22 has array with two objects
    B22: [ {id: "2", name: "Brain"},
           {id: "3", name: "Andy"}
         ]
}

这篇关于将JavaScript项目按一个属性分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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