Вопрос

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"
  }
}
Это было полезно?

Решение 2

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);

Другие советы

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.

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

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}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top