JavaScript组对象 [英] JavaScript group objects

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

问题描述

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

I have been looking for a few days now and I haven't found the answer to this specific problem. I'm receiving a javascript object array from an endpoint in my API. I need to group the objects together based on the Type.

示例硬编码的对象数组:

example hard-coded array of objects:

$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]接下来我需要做的是比较事物[]中的所有对象,使得

typeArr is now going to be [load, export] What I need to happen next is to compare all the objects in things[ ] such that

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

将像这样推动该对象:

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

    ]
]

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

in other words, I need the objects to remain whole, and I need to categorize them, and nest them according to a shared type. I have seriously been stuck on this all week. Any insight would be greatly appreciated.

推荐答案

尝试一下

   
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组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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