我在javascript中有以下JSON对象数组:
[{ "AuthorName" : "Abc", "BookName" : "book-1" }]
[{ "AuthorName" : "Abc", "BookName" : "book-2" }]
[{ "AuthorName" : "Abc", "BookName" : "book-3" }]
[{ "AuthorName" : "Abc", "BookName" : "book-4" }]现在,我想从上面的JSON对象数组创建一个JSON对象。新创建的单个JSON对象包含两个属性:AuthorName和BooKName数组。我正在尝试实现这样的目标:
{ "AuthorName" : "Abc", "Book" : ['book-1', 'book-2', 'book-3', 'book-4'] }现在我的问题是,我如何才能高效地实现这一点,并且用javascript编写最少的代码呢?
发布于 2012-10-23 03:27:07
var obj = {};
for(var i=0; i<myArray.length; i++) {
if(obj[myArray[i].AuthorName] == null)
obj[myArray[i].AuthorName] = [];
obj[myArray[i].AuthorName].push(myArray[i].BookName)
}发布于 2012-10-23 03:36:26
希望这能有所帮助:
var bookSort = function (bookarray) {
var i,
book,
authorArray = [],
il = bookarray.length,
j,
jl,
authorInArray;
for (i = 0; i < il; i++) {
authorInArray= false;
jl = authorArray.length;
book = bookArray[i];
for (j = 0; j < jl; j++) {
if (book.AuthorName = authorArray[j].AuthorName) {
authorInArray= true;
authorArray[j].BookName.push(book.BookName);
break;
}
}
if (!authorInArray) {
authorArray.push({AuthorName: book.AuthorName, BookName: [book.BookName]});
}
}
return authorArray;
};发布于 2012-10-23 04:07:57
看起来你需要一个组合多个对象的函数。
如果你创建了一个通用的函数来做这件事,你可以重用它。我不鼓励你创建一个像authorArray之类的硬编码的解决方案。
让我们创建一个接受多个对象并将它们组合在一起的函数。让我们保持简单,并假设对象看起来与您问题中的对象相似。换句话说,要组合的对象将仅仅是名称值对的平面列表。这些值可以是字符串,也可以是字符串数组。
jsFiddle Demo
// A function that combines multiple object.
// The original objects are made of name value pairs where the values are strings.
// If - for a key - the values are the same, the value is kept
// If - for a kye - the values are different, and array is created and the values pushed to it
// after this all new values are added to the array if not already there.
var combineObjects = function() {
// see how many object are to be combined
var length = arguments.length,
i,
// Create a new empty object that will be returned
newObject = {},
objectIn,
prop,
temp,
ii,
alreadyExists;
// Go through all passed in object... combinging them
for (i = 0; i < length; ++i) {
objectIn = arguments[i];
for (prop in objectIn) {
if (objectIn.hasOwnProperty(prop)) {
// Check if the prop exisits
if (newObject[prop]) {
// Check if the prop is a single or multiple (array)
if (Object.prototype.toString.call( newObject[prop] ) === '[object Array]') {
// Multiple
// Check if element is in array
alreadyExists = false;
for (ii = 0; ii < newObject[prop].length; ++ii) {
if (newObject[prop][ii] === objectIn[prop]) {
alreadyExists = true;
break;
}
}
if (! alreadyExists) {
newObject[prop].push(objectIn[prop]);
}
} else {
// Single
if (newObject[prop] !== objectIn[prop]) {
temp = newObject[prop];
newObject[prop] = [temp, objectIn[prop]];
}
}
} else {
newObject[prop] = objectIn[prop];
}
}
}
}
// Alert for testing
alert(JSON.stringify(newObject));
return newObject;
};https://stackoverflow.com/questions/13018312
复制相似问题