如何在javascript中合并多个对象?

时间:2012-10-22 19:23:00

标签: javascript jquery

我在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中编写最少的代码?

5 个答案:

答案 0 :(得分: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)
}

答案 1 :(得分: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;
};

答案 2 :(得分:1)

好像你需要一个组合多个对象的功能。

如果您创建执行此操作的通用功能,则可以重复使用它。我不鼓励你创建一个像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;        
};

答案 3 :(得分: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'] }

答案 4 :(得分: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'] }]

FIDDLE

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

PROOF