-1

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

[
      {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]);    
}
4

2 回答 2

2

你可以这样做:

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

演示(打开控制台)

于 2012-12-10T16:44:10.713 回答
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"]);
于 2012-12-10T16:47:03.490 回答