2

我在 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 对象包含 2 个属性:AuthorNameBooKName数组。我正在尝试实现这样的目标:

{ "AuthorName" : "Abc", "Book" : ['book-1', 'book-2', 'book-3', 'book-4'] }

现在我的问题是,我怎样才能有效地实现这一目标并在 javascript 中编写最少的代码?

4

5 回答 5

2
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-22T19:27:06.710 回答
2

希望这会有所帮助:

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-22T19:36:25.707 回答
1

似乎您需要一个组合多个对象的函数。

如果您创建一个通用功能来执行此操作,则可以重用它。我不鼓励您创建一个包含诸如authorArray硬编码之类的解决方案的解决方案。

让我们创建一个接收多个对象并将它们组合起来的函数。让我们保持简单,并假设对象看起来像您问题中的对象。换句话说,要组合的对象将只是名称值对的平面列表。这些值将是一个字符串或一个字符串数组。

jsFiddle 演示

// 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;        
};
于 2012-10-22T20:07:56.573 回答
0

不知道你在追求什么。也许这对你有用:

var books = [ 
  [{ "AuthorName" : "Abc", "BookName" : "book-1" }],
  [{ "AuthorName" : "Abc", "BookName" : "book-2" }],
  [{ "AuthorName" : "Abc", "BookName" : "book-3" }],
  [{ "AuthorName" : "Abc", "BookName" : "book-4" }]
];    

// First book in the array
var first = books[0][0];

// Add BookName property to the first book object (BookNames would be a better name)
first.BookName = books.map(function(book, n) {
  return book[0].BookName;
});

/*
  Or, use jQuery.map if you got a older browser that don't support the Array.map function
  $.map(books, function(book, n) {
     return book[0].BookName;
  });
 */

// first is now:
{ AuthorName : "Abc", BookName : ['book-1', 'book-2', 'book-3', 'book-4'] }
于 2012-10-22T20:10:02.607 回答
0

看起来这些只是四个包含对象的单独数组。

如果将这四个单独的数组放在另一个数组中,以便可以迭代它们,如下所示:

var a = [
        [{ AuthorName : 'Abc', BookName : 'book-1'}],
        [{ AuthorName : 'Abc', BookName : 'book-2'}],
        [{ AuthorName : 'Abc', BookName : 'book-3'}],
        [{ AuthorName : 'Abc', BookName : 'book-4'}]
        ];

我只是这样做:

var new_array = [],
    temp_obj = {};

$.each(a, function(i,e) {
    var author = e[0].AuthorName,
        book   = e[0].BookName;
    temp_obj[author] ? temp_obj[author].push(book) : temp_obj[author] = [book];
});

$.each(temp_obj, function(author,books) {
    var obj = {AuthorName: author, BookName : books};
    new_array.push(obj);
});

//new_array is now = [{ AuthorName : 'Abc', BookName : ['book-1', 'book-2', 'book-3', 'book-4'] }]

小提琴

它还会整理出更多的作者和书籍等吗?

证明

于 2012-10-22T20:10:15.667 回答