且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将JavaScript项目按一个属性分组

更新时间:2023-01-08 15:58:17

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

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"}
         ]
}