JavaScript 组对象

标签 javascript angularjs underscore.js

我已经找了几天了,但还没有找到这个具体问题的答案。我正在从 API 中的端点接收 JavaScript 对象数组。我需要根据类型将对象分组在一起。

硬编码对象数组示例:

$scope.content = {
    things: [
        {
            thing: 'one',
            thingType: 'load'
        },
        {
            thing: 'two',
            thingType: 'export'
        },
        {
            thing: 'three',
            thingType: 'export'
        }
    ]
}
var typeArr = [];
for (var key in $scope.content.things) {

     typeArr[key] = $scope.content.things[key].thingType;
}
typeArr = _.uniq(typeArr);

typeArr 现在将是 [load, export] 接下来我需要比较 things[ ] 中的所有对象,使得

 if(typeArr[key] === things[i].thingType) 

会像这样插入该对象:

typeArr = [
    load: {
        thing: 'one',
        thingType: 'load'
    },
    export: [{
        thing: 'two',
        thingType: 'export'
    },
    {
        thing: 'three',
        thingType: 'export'
     }

    ]
]

换句话说,我需要对象保持完整,我需要对它们进行分类,并根据共享类型嵌套它们。我整个星期都被这个问题严重困扰了。任何见解将不胜感激。

最佳答案

试试这个

   
var content = {
    things: [
        {
            thing: 'one',
            thingType: 'load'
        },
        {
            thing: 'two',
            thingType: 'export'
        },
        {
            thing: 'three',
            thingType: 'export'
        }
    ]
}
var typeArr = {};
content.things.forEach(function(item){
    typeArr[item.thingType] = typeArr[item.thingType]||[];
    typeArr[item.thingType].push(item);
});

document.body.innerHTML = JSON.stringify(typeArr);

关于JavaScript 组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373760/

相关文章:

javascript - AngularJS 上的自动空值

javascript - d3.js div 工具提示不再出现在 wordpress 中

javascript - 发出 RESTful JSON 请求

javascript - $http({method}) 不工作,但 $http.get 工作

javascript - angular 在过滤器中从 $rootScope 调用实用函数

javascript - 下划线: Losing reference to collection when filtering

javascript - 使用任何 lodash 获取嵌套 JSON 对象的所有值

javascript - 使用 lodash 下划线比较重复电子邮件列表

javascript - AngularJS select2 不显示任何值

javascript - 将属性添加到同一索引处数组中索引处的对象