如何从键值对数组中创建对象? [英] How to create an object from an Array of key-value pairs?

查看:135
本文介绍了如何从键值对数组中创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,可以将 dict 1 构造函数传递给一系列键值对:

In Python one can pass the dict1 constructor a sequence of key-value pairs:

>>> dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']])
{'age': 42, 'name': 'Bob', 'breakfast': 'eggs'}

我想不出有任何办法做这种事除了为此目的定义我自己的函数之外的JavaScript中的东西:

I can't think of any way to do this sort of thing in JavaScript other than defining my own function for the purpose:

function pairs_to_object(pairs) {
    var ret = {};
    pairs.forEach(function (p) { ret[p[0]] = p[1]; });
    return ret;
}

但我是JS noob ......有没有内置的东西对于这种对 - 对象转换?

But I'm a JS noob... Is there anything built-in for this sort pairs-to-object conversion?

1 出于这个问题的目的,我将Python dicts视为Python与JS对象的对应关系,当然,相似性仅限于它们都是键值集合的事实。

1 For the purposes of this question, I'm treating Python dicts as Python's counterpart of JS objects, although, of course the similarity is limited only to the fact that they are both key-value collections.

推荐答案

JavaScript对象/字典/关联数组本身没有这样的构造函数。

JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.

正如您自己所说,您当然可以使用 reduce 使用功能方法构建自己的函数功能如其他答案之一所述。当然,经典或更新的forEach循环也可以使用。但是没有任何内置的东西。

As you said yourself, you can of course build your own function using for instance a functional approach using the reduce function as explained in one of the other answers. A classic for or newer forEach loop would also work, of course. But there isn't anything built-in.

这篇关于如何从键值对数组中创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆