-1

Suppose we have a java script objects on array like this:

lets say i have a variable books having collection of book

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

And lets say every writer have a book name inside their info like this

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'
    }
}

I want to merge these javascript objects to this one :

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',
            },
        },
     }
}

I tried using underscore foreach but it gets terribly complicated like too much loop inside loop. I think there are certainly good way to do it :)

Is there anyway?

Thanks

1 Answers1

0

You can iterate both objects if they have an id:

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

Or declare them as arrays:

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

Then you can do do the 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
                }
            }
        }
    }
}

As an object result[1] will be the book with id 1. As an array result[0] will be the book with id "X".

DomeTune
  • 1,401
  • 10
  • 21