如何使用java脚本对象数组进行排序以相对于对象数组中的字段进行映射

时间:2012-12-10 16:38:18

标签: javascript

我有一个像这样的对象数组

[
      {bookName:"javascript",authorName:"john"},
      {bookName:"java",authorName:"peter"},
      {bookName:"j2ee",authorName:"john"},
      {bookName:".net",authorName:"peter"},
      {bookName:"oracle",authorName:"peter"}];

我尝试了逻辑,但我没有得到正确的结果。我想这样解决..

{
peter:{
    [{bookName:"java",authorName:"peter"},

    {bookName:".net",authorName:"peter"},

    {bookName:"oracle",authorName:"peter"} ]

     } ,
john :{
    [{bookName:"j2ee",authorName:"john"},

    {bookName:"javascript",authorName:"john"}]

    }

}.

我怎么能这样做..先谢谢你..

var obj={};
var objArr = given objectarray;
for(var i=0;i<objArr.length.i++ ){
  objArr[objArr[i].authorName]=objArr[i];    
}

var obj={};
var objArr = given objectarray;
for(var i=0;i<objArr.length.i++ ){
  var arr=[];
  objArr[objArr[i].authorName]=arr.push(objArr[i]);    
}

2 个答案:

答案 0 :(得分:2)

你可以这样做:

var b = ... your object ...
var m = {};
b.map(function(v){(m[v.authorName]=m[v.authorName]||[]).push(v)});

Demonstration (open the console)

答案 1 :(得分:1)

http://jsfiddle.net/azqRu/

var array = [
          {bookName:"javascript",authorName:"john"},
          {bookName:"java",authorName:"peter"},
          {bookName:"j2ee",authorName:"john"},
          {bookName:".net",authorName:"peter"},
          {bookName:"oracle",authorName:"peter"}
    ];

    var items = {};
    for(var i = 0, ii = array.length; i < ii; i++) {
        var cell = array[i];
        items[cell.authorName] = items[cell.authorName] || [];
        items[cell.authorName].push(cell);
    }    

    alert(items["peter"]);