In Python one can pass the dict
1 constructor a sequence of key-value pairs:
在Python中,可以将dict1构造函数传递给一系列键值对:
>>> dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']])
{'age': 42, 'name': 'Bob', 'breakfast': 'eggs'}
I can't think of any way to do this sort of thing in JavaScript other than defining my own function for the purpose:
除了为此目的定义我自己的函数之外,我想不出用JavaScript做任何事情的方法:
function pairs_to_object(pairs) {
var ret = {};
pairs.forEach(function (p) { ret[p[0]] = p[1]; });
return ret;
}
But I'm a JS noob... Is there anything built-in for this sort pairs-to-object conversion?
但我是一个JS noob ......对于这种对 - 对象转换,有没有内置的东西?
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.
1出于这个问题的目的,我将Python dicts视为Python对象的JS对象,当然,相似性仅限于它们都是键值集合的事实。
5 个解决方案
#1
10
JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.
JavaScript对象/字典/关联数组本身没有这样的构造函数。
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.
正如您自己所说,您当然可以使用reduce函数构建自己的函数,例如使用reduce函数,如其他答案中所述。当然,经典或更新的forEach循环也可以使用。但是没有任何内置的东西。
#2
32
You can use the reduce function
您可以使用reduce功能
x = [[1,2],[3,4],[5,6]];
o = x.reduce(function(prev,curr){prev[curr[0]]=curr[1];return prev;},{})
o is now the equivalent of {1:2, 3:4, 5:6}
o现在相当于{1:2,3:4,5:6}
If your input array is sparse, you'll want to add a if(curr!=undefined)
test on the assignment, but make sure you still return "prev".
如果输入数组稀疏,则需要在赋值时添加if(curr!= undefined)测试,但请确保仍返回“prev”。
If your tuples are something more complex than simple [key,value], you can simply change the way "prev" is assigned to. Eg: prev["key-"+curr[0].toString()]=curr[1]*2;
如果你的元组比简单的[key,value]更复杂,你可以简单地改变“prev”的分配方式。例如:prev [“key - ”+ curr [0] .toString()] = curr [1] * 2;
#3
20
In ES6 you could define that dict function like this:
在ES6中你可以像这样定义dict函数:
const dict = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
// Demo:
const obj = dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']]);
console.log(obj);
Instead of calling it dict, you could define it on Object
, and call it from
:
您可以在Object上定义它,而不是将其命名为dict,并从以下位置调用它:
Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
A nice thing is that this method does the opposite of Object.entries
(ES2017), so now you can go back and forth between the object and array representation:
一个好处是这个方法与Object.entries(ES2017)相反,所以现在你可以在对象和数组表示之间来回:
Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
// Demo:
const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
const arr2 = Object.entries(Object.from(arr));
console.log(arr2); // copy of the original array (omitting duplicate keys)
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 Map
There is an alternative to plain objects for key/value pairs: Map
.
对于键/值对,可以使用普通对象的替代方法:Map。
Its constructor accepts the array-of-pairs format:
它的构造函数接受数组对的格式:
// Demo:
const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
const mp = new Map(arr);
// Get one particular value:
console.log(mp.get('age'));
// Get all the keys:
console.log(...mp.keys());
// Get all the values:
console.log(...mp.values());
// Get all the key/value pairs:
console.log(...mp.entries());
If you really need a plain object, then this is not useful, but a Map might present a viable alternative.
如果你真的需要一个普通的对象,那么这没用,但Map可能会提供一个可行的选择。
#4
4
Lodash's fromPairs function will do this:
Lodash的fromPairs函数将执行此操作:
const _ = require('lodash')
const kvPairs = [['a', 1], ['b', 2]]
_.fromPairs(kvPairs)
// => { a: 1, b: 2 }
#5
1
Javascript does not have a native function for converting an array into an object in the way you have described. But, this is because there is no need for it. You have already included in the question an example solution, where you define the function yourself, but that really isn't necessary. As long as you can be sure that the input array is correct, you could even do the conversion with a simple for loop, like so:
Javascript没有以您所描述的方式将数组转换为对象的本机函数。但是,这是因为没有必要。您已经在问题中包含了一个示例解决方案,您可以自己定义该函数,但实际上并不是必需的。只要您可以确定输入数组是正确的,您甚至可以使用简单的for循环进行转换,如下所示:
var input = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
var output = {};
for(i in input) output[input[i][0]] = input[i][1];
Which is just about the most basic code imaginable.
这是可以想象的最基本的代码。
Of course, (as mamapitufo points out) it is generally a bad idea to actually use for..in to iterate over an array, because that will also return non-indexes as values of i. Still, the point is that this kind of operation is too simple, and too rarely needed, to justify having a native function.
当然,(正如mamapitufo指出的那样)实际上使用for..in迭代数组通常是一个坏主意,因为这也会将非索引作为i的值返回。不过,重点是这种操作过于简单,而且很少需要,以证明具有本机功能。
The python dict is a structure which is not needed in javascript, because the two languages have different approaches to typing, and to design in general, and so what is useful to one is not useful to another. While you could work on using the same methods and structures that you used in python, it might be a better idea to think about how to take advantage of javascript's different way of doing things - maybe you will find that you don't need a dict after all.
python dict是javascript中不需要的结构,因为这两种语言有不同的键入和设计方法,因此对一个语言有用的对另一个语言没用。虽然你可以使用你在python中使用的相同方法和结构,但考虑如何利用javascript不同的做事方式可能是一个更好的主意 - 也许你会发现你不需要一个字典毕竟。
#1
10
JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.
JavaScript对象/字典/关联数组本身没有这样的构造函数。
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.
正如您自己所说,您当然可以使用reduce函数构建自己的函数,例如使用reduce函数,如其他答案中所述。当然,经典或更新的forEach循环也可以使用。但是没有任何内置的东西。
#2
32
You can use the reduce function
您可以使用reduce功能
x = [[1,2],[3,4],[5,6]];
o = x.reduce(function(prev,curr){prev[curr[0]]=curr[1];return prev;},{})
o is now the equivalent of {1:2, 3:4, 5:6}
o现在相当于{1:2,3:4,5:6}
If your input array is sparse, you'll want to add a if(curr!=undefined)
test on the assignment, but make sure you still return "prev".
如果输入数组稀疏,则需要在赋值时添加if(curr!= undefined)测试,但请确保仍返回“prev”。
If your tuples are something more complex than simple [key,value], you can simply change the way "prev" is assigned to. Eg: prev["key-"+curr[0].toString()]=curr[1]*2;
如果你的元组比简单的[key,value]更复杂,你可以简单地改变“prev”的分配方式。例如:prev [“key - ”+ curr [0] .toString()] = curr [1] * 2;
#3
20
In ES6 you could define that dict function like this:
在ES6中你可以像这样定义dict函数:
const dict = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
// Demo:
const obj = dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']]);
console.log(obj);
Instead of calling it dict, you could define it on Object
, and call it from
:
您可以在Object上定义它,而不是将其命名为dict,并从以下位置调用它:
Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
A nice thing is that this method does the opposite of Object.entries
(ES2017), so now you can go back and forth between the object and array representation:
一个好处是这个方法与Object.entries(ES2017)相反,所以现在你可以在对象和数组表示之间来回:
Object.from = arr => Object.assign(...arr.map( ([k, v]) => ({[k]: v}) ));
// Demo:
const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
const arr2 = Object.entries(Object.from(arr));
console.log(arr2); // copy of the original array (omitting duplicate keys)
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 Map
There is an alternative to plain objects for key/value pairs: Map
.
对于键/值对,可以使用普通对象的替代方法:Map。
Its constructor accepts the array-of-pairs format:
它的构造函数接受数组对的格式:
// Demo:
const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
const mp = new Map(arr);
// Get one particular value:
console.log(mp.get('age'));
// Get all the keys:
console.log(...mp.keys());
// Get all the values:
console.log(...mp.values());
// Get all the key/value pairs:
console.log(...mp.entries());
If you really need a plain object, then this is not useful, but a Map might present a viable alternative.
如果你真的需要一个普通的对象,那么这没用,但Map可能会提供一个可行的选择。
#4
4
Lodash's fromPairs function will do this:
Lodash的fromPairs函数将执行此操作:
const _ = require('lodash')
const kvPairs = [['a', 1], ['b', 2]]
_.fromPairs(kvPairs)
// => { a: 1, b: 2 }
#5
1
Javascript does not have a native function for converting an array into an object in the way you have described. But, this is because there is no need for it. You have already included in the question an example solution, where you define the function yourself, but that really isn't necessary. As long as you can be sure that the input array is correct, you could even do the conversion with a simple for loop, like so:
Javascript没有以您所描述的方式将数组转换为对象的本机函数。但是,这是因为没有必要。您已经在问题中包含了一个示例解决方案,您可以自己定义该函数,但实际上并不是必需的。只要您可以确定输入数组是正确的,您甚至可以使用简单的for循环进行转换,如下所示:
var input = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
var output = {};
for(i in input) output[input[i][0]] = input[i][1];
Which is just about the most basic code imaginable.
这是可以想象的最基本的代码。
Of course, (as mamapitufo points out) it is generally a bad idea to actually use for..in to iterate over an array, because that will also return non-indexes as values of i. Still, the point is that this kind of operation is too simple, and too rarely needed, to justify having a native function.
当然,(正如mamapitufo指出的那样)实际上使用for..in迭代数组通常是一个坏主意,因为这也会将非索引作为i的值返回。不过,重点是这种操作过于简单,而且很少需要,以证明具有本机功能。
The python dict is a structure which is not needed in javascript, because the two languages have different approaches to typing, and to design in general, and so what is useful to one is not useful to another. While you could work on using the same methods and structures that you used in python, it might be a better idea to think about how to take advantage of javascript's different way of doing things - maybe you will find that you don't need a dict after all.
python dict是javascript中不需要的结构,因为这两种语言有不同的键入和设计方法,因此对一个语言有用的对另一个语言没用。虽然你可以使用你在python中使用的相同方法和结构,但考虑如何利用javascript不同的做事方式可能是一个更好的主意 - 也许你会发现你不需要一个字典毕竟。