合并两个javascript对象

时间:2017-01-06 12:36:54

标签: javascript

假设我们在数组上有一个java脚本对象:

假设我有一本可变书籍,有书籍集合

var books ={
  {
    id: 1,
    name: 'Physics'
 }
 {
    id: 2,
    name: 'Mathematics'
 }
 {
    id: 3,
    name: 'Chemistry'
 }
}

并且让我们说每个作家在他们的信息中都有一个书名,如

var writers ={

    {
        id: 123,
        name: 'William Jeff',
        book:  'Physics'
    },

    {
        id: 123123,
        name: 'John Doe',
        book: 'Mathematics'
    },
    {
        id: 1212312323,
        name: 'asd Doe',
        book: 'Chemistry'
    },
    {
        id:123123,
        name: 'ASD DAS',
        book:'Physics'
    }
}

我想将这些javascript对象合并到这个:

var result = {
    {
    id: 1,
    name: 'Physics',
    writers : {
        {
            id: 123,
            name: 'William Jeff',
        },
        {
            id:123123,
            name: 'ASD DAS',
        }
    },

    {
        id: 2,
        name: 'Mathematics'
        writers : {
            {
                id: 123123,
                name: 'John Doe',
            }
        },
     }
    {
        id: 3,
        name: 'Chemistry',
        writers : {
            {
                id: 1212312323,
                name: 'asd Doe',
            },
        },
     }
}

我尝试使用下划线foreach但是它变得非常复杂,就像循环中的循环太多。我认为当然有很好的方法:)

还有吗?

谢谢

1 个答案:

答案 0 :(得分:0)

如果对象具有id:

,则可以迭代这两个对象
var books = { 1: { id: 1, name: "Math" }, ...}
var writers = { 1: { id:1, name: "John Doe", book: "Math"}, ...}

或者将它们声明为数组:

var books = [{ id: 1, name: "Math" }, ...]
var writers = [{ id:1, name: "John Doe", book: "Math"}, ...]

然后你可以做for-loops

var result = {}; //or as an array
for(bookKey in books){
    var book = books[bookKey];
    for(writerKey in writers){
        var writer = writers[writerKey];
        if(writer.book == book.name){
            result[bookKey] = { //for an array: result.push(object)
                id: book.id,
                name: book.name,
                writer: {
                    id: writer.id,
                    name: write.name
                }
            }
        }
    }
}

作为对象结果[1]将是id为1的书。 作为数组结果[0]将是具有id" X"。

的书