Merge keys array and values array into an object in JavaScript

Viewed 42912

I have:

var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];

And I'd like to convert it into this object:

{ height: "12px", width: "24px" }

In Python, there's the simple idiom dict(zip(keys,values)). Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?

13 Answers

The simplest ES6 one-liner solution using Array reduce:

const keys = ['height', 'width'];
const values = ['12px', '24px'];
const merged = keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {});

Simple JS function would be:

function toObject(names, values) {
    var result = {};
    for (var i = 0; i < names.length; i++)
         result[names[i]] = values[i];
    return result;
}

Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D

As an alternate solution, not already mentioned I think :

  var result = {};
  keys.forEach((key, idx) => result[key] = values[idx]);

You can combine two arrays with map method, then convert it with Object.fromEntries.

var keys = ["height", "width"];
var values = ["12px", "24px"];

var array = keys.map((el, i) => {
  return [keys[i], values[i]];
});
// → [["height", "12px"], ["width", "24px"]]

var output = Object.fromEntries(array);
// → {height: "12px", width: "24px"}
console.log(output);

A functional approach with immutability in mind:

const zipObj = xs => ys => xs.reduce( (obj, x, i) => ({ ...obj, [x]: ys[i] }), {})

const arr1 = ['a', 'b', 'c', 'd']
const arr2 = ['e', 'f', 'g', 'h']

const obj = zipObj (arr1) (arr2) 

console.log (obj)

Now we have Object.fromEntries we can do something like that:

const keys = [ "height", "width" ];
const values = [ "12px", "24px" ];
const myObject = Object.fromEntries(
    values.map((value, index) => [keys[index], value])
);

console.log(myObject);

Here's an example with all consts (non-modifying) and no libraries.

const keys = ["Adam", "Betty", "Charles"];
const values = [50, 1, 90];
const obj = keys.reduce((acc, key, i) => {
  acc[key] = values[i];
  return acc;
}, {});
console.log(obj);

Alternatively, if you'd consider libraries you could use lodash zipobject which does just what you asked.

function combineObject( keys, values)
{
    var obj = {};
    if ( keys.length != values.length)
       return null;
    for (var index in keys)
        obj[keys[index]] = values[index];
     return obj;
};


var your_obj = combine( your_keys, your_values);

You could transpose the arrays and get the object with the entries.

const
    transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
    keys = [ "height", "width" ],
    values = [ "12px", "24px" ],
    result = Object.fromEntries([keys, values].reduce(transpose, []));

console.log(result);

Here's one which will transform nested arrays into an array of multiple key-value objects.

var keys = [
  ['#000000', '#FFFFFF'],
  ['#FFFF00', '#00FF00', '#00FFFF', '#0000FF'],
];
var values = [
  ['Black', 'White'],
  ['Yellow', 'Green', 'Cyan', 'Blue'],
];
const zipObj = xs => ys => xs.reduce( (obj, x, i) => ({ ...obj, [x]: ys[i] }), {})
var array = keys.map((el, i) => zipObj (keys[i]) (values[i]));

console.log(array);

Output is

[
  {
    "#000000": "Black",
    "#FFFFFF": "White"
  },
  {
    "#FFFF00": "Yellow",
    "#00FF00": "Green",
    "#00FFFF": "Cyan",
    "#0000FF": "Blue"
  }
]

In the jQuery-Utils project, the ArrayUtils module has a zip function implemented.

//...
zip: function(object, object2, iterator) {
    var output = [];
    var iterator = iterator || dummy;
        $.each(object, function(idx, i){
        if (object2[idx]) { output.push([i, object2[idx]]); }
    });
    return output;
}
//...
Related