1

I'm looking for a native JavaScript method to merge 2 arrays into a literal object.

Turn this:

var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"]; 
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];

Into this:

{
"obj" : {
    "blue" : "james",
    "yellow" : "john",
    "red" :  "robert", 
    "green" : "michael", 
    "brown" : "william", 
    "gray" : "david", 
    "grey" : "richard", 
    "orange" : "wayne"
  }
}
4
  • 1
    The arrays will always be of the same size? Commented Jun 2, 2013 at 4:01
  • 2
    "I'm looking for..." - No, you're asking for. What have you tried so far? Commented Jun 2, 2013 at 4:03
  • @BrunoLM in theory the arrays will always be the same size unless something goes completely sideways. Commented Jun 2, 2013 at 4:23
  • @nnnnnn thanks for the link. Yes, I should have posted with source and where I was stuck. The bracket notation "obj[a[i]]" was something I completely overlooked. +1 for the good read. Commented Jun 2, 2013 at 4:55

4 Answers 4

4

You can do this with a fairly simple loop:

var result = {obj: {}};
for (var i=0; i<x.length; i++) {
    result.obj[x[i]] = y[i];
}

This assumes that x and y are always the same length. If they're not, you just need to add a bit more code for checking the lengths.

Sign up to request clarification or add additional context in comments.

Comments

3
var x = ["blue", "yellow", "red", "green", "brown", "grey", "gray", "orange"]; 
var y = ["james", "john", "robert", "michael", "william", "david", "richard", "wayne"];

function merge2array(a, b) {
    var obj = {};
    var l = a.length;
    var i;

    for (i = 0; i < l; i++) {
        obj[a[i]] = b[i];
    }

    return obj;
}

var obj = merge2array(x, y);
console.log(obj);

This will return this object:

{
    "blue" : "james",
    "yellow" : "john",
    "red" :  "robert", 
    "green" : "michael", 
    "brown" : "william", 
    "gray" : "david", 
    "grey" : "richard", 
    "orange" : "wayne"
}

Then you can build your desired object:

var r = { obj: obj };
console.log(r);

Comments

0

There isn't a native method.

Here you can find two ways of achieving it

The first method, m1, will validate the length of your arrays, if it doesn't match it will throw an exception.

function m1(keys, values)
{
    // in case the arrays have different sizes
    if (keys.length != values.length)
        throw new Error("Arrays are not of the same size");

    var result = {};
    for (var i in keys)
    {
        result[keys[i]] = values[i];
    }

    return result;
}

The second method, m2, will allow you to have more keys than values, and fill the missing values with null.

function m2(keys, values)
{
    // alternative handling for different sizes
    if (keys.length < values.length)
        throw new Error("You can't have more values than keys");

    var result = {};
    for (var i in keys)
    {
        var val = null;
        if (i < values.length)
            val = values[i];

        result[keys[i]] = val;
    }

    return result;
}

Both methods return an object, to have an object exactly as you described you will can do this:

var x = {};
x.obj = m1([1, 2, 3], ["a", "b", "c"]);

For a compact version (without validations) you can use:

function m(k,v){r={};for (i in k)r[k[i]]=v[i];return r}

Usage:

var x = { obj: m([1,2],["A","B"]) };

Change m to the desired function name.

Reference

Comments

0

fastest(using while--,caching length) / shortest way?

var a=['blue','yellow','red','green','brown','grey','gray','orange'],
b=['james','john','robert','michael','william','david','richard','wayne'],
c=[],d=a.length;while(d--)c[a[d]]=b[d];
var x={obj:c};

also as function (c&d are placeholder so you don't need to write var and save bytes) the name of the function can be placed infront or after 'function'...whatever

function(a,b,c,d){c=[],d=a.length;while(d--)c[a[d]]=b[d];return c}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.