将键数组和值数组合并到Javascript中的对象中

时间:2022-09-25 08:15:20

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?

在Python中,有简单的成语dict(zip(keys,values))。在jQuery或普通的Javascript中是否有类似的东西,或者我必须做很长的事情吗?

8 个解决方案

#1


Simple JS function would be:

简单的JS功能是:

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

当然,您也可以实现像zip等功能,因为JS支持更高阶的类型,这使得这些功能语言易于使用:D

#2


use lodash.

_.zipObject

Example

_.zipObject(['a', 'b'], [1, 2]);
// ➜ { 'a': 1, 'b': 2 }

#3


As an alternate solution, not already mentioned I think :

作为替代解决方案,我还没有提到:

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

#4


The simplest ES6 one-liner solution using Array reduce:

使用Array的最简单的ES6单线解决方案减少:

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

#5


You could use a reduce() function to map the key-value pairs to an object.

您可以使用reduce()函数将键值对映射到对象。

/**
 *  Apply to an existing or new object, parallel arrays of key-value pairs.
 *
 *  @param   {string[]} keys      - List of keys corresponding to their accociated values.
 *  @param   {object[]} vals      - List of values corresponding to their accociated keys.
 *  @param   {object}   [ref={}]  - Optional reference to an existing object to apply to.
 *
 *  @returns {object} - The modified or new object with the new key-value pairs applied.
 */
function toObject(keys, vals, ref) {
  return keys.length === vals.length ? keys.reduce(function(obj, key, index) {
    obj[key] = vals[index];
    return obj;
  }, ref || {}) : null;
}

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

document.body.innerHTML = '<pre>' + JSON.stringify(toObject(keys, values), null, 2) + '</pre>';

#6


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

#7


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)

#8


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

在jQuery-Utils项目中,ArrayUtils模块实现了zip功能。

//...
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;
}
//...

#1


Simple JS function would be:

简单的JS功能是:

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

当然,您也可以实现像zip等功能,因为JS支持更高阶的类型,这使得这些功能语言易于使用:D

#2


use lodash.

_.zipObject

Example

_.zipObject(['a', 'b'], [1, 2]);
// ➜ { 'a': 1, 'b': 2 }

#3


As an alternate solution, not already mentioned I think :

作为替代解决方案,我还没有提到:

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

#4


The simplest ES6 one-liner solution using Array reduce:

使用Array的最简单的ES6单线解决方案减少:

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

#5


You could use a reduce() function to map the key-value pairs to an object.

您可以使用reduce()函数将键值对映射到对象。

/**
 *  Apply to an existing or new object, parallel arrays of key-value pairs.
 *
 *  @param   {string[]} keys      - List of keys corresponding to their accociated values.
 *  @param   {object[]} vals      - List of values corresponding to their accociated keys.
 *  @param   {object}   [ref={}]  - Optional reference to an existing object to apply to.
 *
 *  @returns {object} - The modified or new object with the new key-value pairs applied.
 */
function toObject(keys, vals, ref) {
  return keys.length === vals.length ? keys.reduce(function(obj, key, index) {
    obj[key] = vals[index];
    return obj;
  }, ref || {}) : null;
}

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

document.body.innerHTML = '<pre>' + JSON.stringify(toObject(keys, values), null, 2) + '</pre>';

#6


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

#7


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)

#8


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

在jQuery-Utils项目中,ArrayUtils模块实现了zip功能。

//...
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;
}
//...