通过javascript中的属性对JSON数组进行排序? [英] Sort JSON array by a property in javascript?

查看:82
本文介绍了通过javascript中的属性对JSON数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以

这是我的JSON数据的非常简化的版本:

This is a very simplified version of my JSON data:

 [
  {
    "category": "Financial",
    "item": "DIAS"
  },
  {
    "category": "Social",
    "item": "Andrew Barnett Explains..."
  },
  {
    "category": "Financial",
    "item": "FP Sales"
  }
]

我想按以下方式安排它:

and I want to arrange it like the following:

[
  {
    "category": "Financial",
    "items": [
      {
        "item": "DIAS"
      },
      {
        "item": "FP Sales"
      }
    ]
  },
  {
    "category": "Social",
    "items": [
      {
        "item": "Andrew Barnett Explains..."
      }
    ]
  }
]

实现此目标的最佳方法是什么?我确定有比使用两个循环更好的方法了吗?

What is the best way (performance wise) to achieve this? I am sure there is a better way than using two loops?

谢谢

推荐答案

我整理了一些可行的方法: http://jsfiddle.net/Hnj2s/

I have put together a fiddle of something that works: http://jsfiddle.net/Hnj2s/

var temp =  [
  {
    "category": "Financial",
    "item": "DIAS"
  },
  {
    "category": "Social",
    "item": "Andrew Barnett Explains..."
  },
  {
    "category": "Financial",
    "item": "FP Sales"
  }
];

var output = [];
var lookup = {};
for(var i=0; i<temp.length; i+=1){
    var cat = temp[i].category;
    if(!lookup[cat]){
        lookup[cat] = {
            category: cat,
            items: []   
        };
        output.push(lookup[cat]);           
    }
    lookup[cat].items.push({
        item: temp[i].item
    });
}

console.log(output);

我不确定您如何在此处定义最佳方法,您可能需要具体说明.但是,此方法只能通过单个循环遍历所有项目.

I'm not sure how you define best possible way here, and you might need to be specific. However this method works with a single loop through the items.

这篇关于通过javascript中的属性对JSON数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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