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

时间:2009-07-13 06:18:22

标签: javascript idioms

我有:

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

我想把它转换成这个对象:

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

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

12 个答案:

答案 0 :(得分:17)

简单的JS函数将是:

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

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

答案 1 :(得分:16)

使用lodash。

  

_.zipObject

实施例

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

答案 2 :(得分:8)

作为替代解决方案,我认为尚未提及:

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

答案 3 :(得分:8)

使用数组reduce的最简单的ES6一线解决方案:

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

答案 4 :(得分:3)

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

&#13;
&#13;
/**
 *  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>';
&#13;
&#13;
&#13;

答案 5 :(得分:3)

牢记不变的功能方法:

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)

答案 6 :(得分:2)

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 :(得分:1)

您可以转置数组并获得带有条目的对象。

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

答案 8 :(得分:1)

这是所有const(非修改)且没有库的示例。

final case class KillSwitch[F[_]](stream: Stream[F, Unit], switch: F[Unit])
object KillSwitch {

  def apply[F[_]: Sync]: F[KillSwitch[F]] =
    Ref.of(true).map(switch => KillSwitch(Stream.repeatEval(switch.get).takeWhile(identity).void, switch.set(false)))
}

或者,如果您考虑使用库,则可以使用lodash zipobject来满足您的要求。

答案 9 :(得分:0)

jQuery-Utils project中,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;
}
//...

答案 10 :(得分:0)

您可以使用map方法合并两个数组,然后使用Object.fromEntries进行转换。

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

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

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

答案 11 :(得分:0)

这是将嵌套数组转换为多个键值对象数组的方法。

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

输出为

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