最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
最好的转换方式是什么:
['a','b','c']
to:
{
0: 'a',
1: 'b',
2: 'c'
}
当前回答
ECMAScript 6引入了易于多填充的Object.assign:
Object.assign()方法用于复制所有对象的值 可枚举对象拥有的属性,从一个或多个源对象到目标 对象。它将返回目标对象。
Object.assign({}, ['a','b','c']); // {0:"a", 1:"b", 2:"c"}
数组本身的length属性不会被复制,因为它是不可枚举的。
此外,你可以在对象上使用ES8扩展语法来实现相同的结果:
{ ...['a', 'b', 'c'] }
对于自定义键,您可以使用reduce:
['a', 'b', 'c'].reduce((a, v) => ({ ...a, [v]: v}), {})
// { a: "a", b: "b", c: "c" }
其他回答
我的版本数组json在JS。只需要复制/粘贴并使用它。这是不是很棒?我喜欢我在StackOverflow上发现的这类函数。
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
for(var key in arr) {
var value = arr[key];
if(typeof value == "object") { //Custom handling for arrays
if(is_list) parts.push(array2json(value)); /* :RECURSION: */
else parts[key] = array2json(value); /* :RECURSION: */
} else {
var str = "";
if(!is_list) str = '"' + key + '":';
//Custom handling for multiple data types
if(typeof value == "number") str += value; //Numbers
else if(value === false) str += 'false'; //The booleans
else if(value === true) str += 'true';
else str += '"' + value + '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
parts.push(str);
}
}
var json = parts.join(",");
if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}
快速和肮脏的#2:
var i = 0
, s = {}
, a = ['A', 'B', 'C'];
while( i < a.length ) { s[i] = a[i++] };
FWIW,另一种最近的方法是使用Object. fromentries和Object。条目如下:
const arr = ['a','b','c'];
arr[-2] = 'd';
arr.hello = 'e';
arr.length = 17;
const obj = Object.fromEntries(Object.entries(arr));
...它允许避免将稀疏数组项存储为未定义或空,并保留非索引(例如,非正整数/非数字)键。
{0: "a", 1: "b", 2: "c", "-2": "d", hello: "e"}
(这里的结果与@Paul Draper的对象相同。分配的答案。)
你可能希望加上arr。长度,但不包括在内:
obj.length = arr.length;
最简单的方法如下:
const arr = ['a','b','c'];
let obj = {}
function ConvertArr(arr) {
if (typeof(arr) === 'array') {
Object.assign(obj, arr);
}
这样它只在数组中运行,然而,你可以用let全局对象变量或不带,这取决于你,如果你不带let,只运行object。加勒比海盗,分配({})。
令I = 0; let myArray = ["first", "second", "third", "fourth"]; const arrayToObject = (arr) => 对象。分配(arr{},……。Map (item => ({[i++]: item}))); console.log (arrayToObject (myArray));
或使用
myArray = ["first", "second", "third", "fourth"] console.log (myArray{…})