我有一个像这样的对象数组
[
{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]);
}
答案 0 :(得分:2)
你可以这样做:
var b = ... your object ...
var m = {};
b.map(function(v){(m[v.authorName]=m[v.authorName]||[]).push(v)});
答案 1 :(得分:1)
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"]);