简体   繁体   中英

How to merge the below arrays in javascript?

I have two arrays and I want to join them

function test()
        {

            var arr1 = [
                                {"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
                                {"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}

                        ];
            var arr2 = [
                            {"Deptid":4,"Deptname":"IT"},
                            {"Deptid":1,"Deptname":"HR"},
                            {"Deptid":3,"Deptname":"HW"},
                             {"Deptid":24,"Deptname":"HW4"}
                        ];

            var res = Pack(arr1,arr2);
            console.log(res);
        }

    function Pack() 
    { 

        var args = [].slice.call(arguments);        

        args.join(',');       

        return args;
    }      

I am expecting the output as

[{"Employees":[{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}],"Departments":[{"Deptid":1,"Deptname":"IT"},{"Deptid":2,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"},{"Deptid":4,"Deptname":"SW"}]}] 

But not able to. How to do it?

I have already tried with Concat() function of Javascript but it didn't helped.

NB~ As it can be assumed that there can be variable number of arrays in the Pack function.

你不能做这样的事情:

var newArray = [ { "Employees": arr1, "Departments": arr2 } ]

Try this:

var arr1 = [
                                {"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
                                {"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}

                        ];
            var arr2 = [
                            {"Deptid":4,"Deptname":"IT"},
                            {"Deptid":1,"Deptname":"HR"},
                            {"Deptid":3,"Deptname":"HW"},
                             {"Deptid":24,"Deptname":"HW4"}
                        ];

var json = {};
var jsonArr = [];

json.Employees = arr1;
json.Department = arr2;

jsonArr.push(json);

document.write(JSON.stringify(jsonArr));

From the expected JSON, what you need is neither "merging", nor "concatenation". You want to put an array inside an object.

What you want is below:

var output = [{
    "Employees": arr1,
    "Department": arr2
}];

Note that output is an array according to your expectation. Why you need an array is something I dont understand.

function test() {

        var arr1 = {"Employees" : [
                            {"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},
                            {"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}

                    ]};
        var arr2 = {"Departments":[
                        {"Deptid":4,"Deptname":"IT"},
                        {"Deptid":1,"Deptname":"HR"},
                        {"Deptid":3,"Deptname":"HW"},
                         {"Deptid":24,"Deptname":"HW4"}
                    ]};

        var res = Pack(arr1,arr2);
        console.log(res);
    }

function Pack() 
{ 
    var results = [];
    arguments.forEach(function(element){
        results.push(element);
    });
    return results;
}      

Ok, so i put a little fiddle together for you, Here

Most of your code stays the same, except I added this to your test function:

 var myObjToMerge = [{Employees:[]},{Departments:[]}];
 var res = Pack(myObjToMerge,arr1,arr2);

You need to give 'Pack' some object to merge the arrays to, so I created an arbritary array of objects modeled after your example. Note that this array of objects can come from anywhere and this method doesn't require it to be known ahead of time like some of the other examples.

Then I changed the 'Pack' function:

function Pack() 
    { 
        var objToMerge = arguments[0];
        for(var i = 0;i<objToMerge.length;i++)
        {
            if(arguments.length > i+1)
            {
                var firstProperty = Object.keys(objToMerge[i])[0];
                objToMerge[i][firstProperty]= arguments[i+1];
            }
        }   


        return objToMerge;
    }      

The idea here is that 'Pack' grabs the first argument, your object to merge the remaining arguments into. I would suggest using function parameters, but that is your call.

Then, I iterate through the objects in the objToMerge array (there are two objects: Employees and Departments). I assume that the remaining items in arguments is in the correct order and I grab the next item in arguments and assign to to the first property in the object I am currently looped in.

The line:

var firstProperty = Object.keys(objToMerge[i])[0];

Will return the string value of the first property in an object. We then use this to set the next array in arguments to that property:

objToMerge[i][firstProperty]= arguments[i+1];

there are a great deal of assumptions here and ways to improve, but you can see that it works in the fiddle and you can improve upon it as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM