javascript | Object grouping

后端 未结 10 1273
不思量自难忘°
不思量自难忘° 2020-11-27 05:29

I have an object. It looks like below:

[
  {
    \"name\":\"Display\",
    \"group\":\"Technical detals\",
    \"id\":\"60\",
    \"value\":\"4\"
  },
  {
           


        
10条回答
  •  北海茫月
    2020-11-27 06:04

    Try with something like this:

    function groupBy(collection, property) {
        var i = 0, val, index,
            values = [], result = [];
        for (; i < collection.length; i++) {
            val = collection[i][property];
            index = values.indexOf(val);
            if (index > -1)
                result[index].push(collection[i]);
            else {
                values.push(val);
                result.push([collection[i]]);
            }
        }
        return result;
    }
    
    var obj = groupBy(list, "group");
    

    Keep in mind that Array.prototype.indexOf isn't defined in IE8 and older, but there are common polyfills for that.

提交回复
热议问题