将数组转换为对象

本文翻译自:Convert Array to Object

What is the best way to convert: 转换的最佳方式是什么:

['a','b','c']

to: 至:

{0: 'a',1: 'b',2: 'c'
}

#1楼

参考:https://stackoom.com/question/Hghl/将数组转换为对象


#2楼

Quick and dirty #2: 快速而肮脏的#2:

var i = 0, s = {}, a = ['A', 'B', 'C'];while( a[i] ) { s[i] = a[i++] };

#3楼

Here's a solution in coffeescript 这是coffeescript的解决方案

arrayToObj = (arr) ->obj = {}for v,i in arrobj[i] = v if v?obj

#4楼

This allows you to generate from an array an object with keys you define in the order you want them. 这允许您从数组生成一个对象,该对象具有您按照所需顺序定义的键。

Array.prototype.toObject = function(keys){var obj = {};var tmp = this; // we want the original array intact.if(keys.length == this.length){var c = this.length-1;while( c>=0 ){obj[ keys[ c ] ] = tmp[c];c--;}}return obj;
};result = ["cheese","paint",14,8].toObject([0,"onion",4,99]);

console.log(">>> :" + result.onion); will output "paint", the function has to have arrays of equal length or you get an empty object. 将输出“paint”,该函数必须具有相等长度的数组,否则您将得到一个空对象。

Here is an updated method 这是一个更新的方法

Array.prototype.toObject = function(keys){var obj = {};if( keys.length == this.length)while( keys.length )obj[ keys.pop() ] = this[ keys.length ];return obj;
};

#5楼

You could use an accumulator aka reduce . 你可以使用累加器aka reduce

['a','b','c'].reduce(function(result, item, index, array) {result[index] = item; //a, b, creturn result;
}, {}) //watch out the empty {}, which is passed as "result"

Pass an empty object {} as a starting point; 传递空对象{}作为起点; then "augment" that object incrementally. 然后逐渐“增加”该对象。 At the end of the iterations, result will be {"0": "a", "1": "b", "2": "c"} 在迭代结束时, result将为{"0": "a", "1": "b", "2": "c"}

If your array is a set of key-value pair objects: 如果您的数组是一组键值对对象:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item) {var key = Object.keys(item)[0]; //first property: a, b, cresult[key] = item[key];return result;
}, {});

will produce: {a: 1, b: 2, c: 3} 将产生: {a: 1, b: 2, c: 3}

For the sake of completeness, reduceRight allows you to iterate over your array in reverse order: 为了完整起见, reduceRight允许您以相反的顺序迭代数组:

[{ a: 1},{ b: 2},{ c: 3}].reduceRight(/* same implementation as above */)

will produce: {c:3, b:2, a:1} 将产生: {c:3, b:2, a:1}

Your accumulator can be of any type for you specific purpose. 您的累加器可以是任何类型的特定用途。 For example in order to swap the key and value of your object in an array, pass [] : 例如,为了在数组中交换对象的键和值,传递[]

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {var key = Object.keys(item)[0]; //first property: a, b, cvar value = item[key];var obj = {};obj[value] = key;result.push(obj);return result;
}, []); //an empty array

will produce: [{1: "a"}, {2: "b"}, {3: "c"}] 将产生: [{1: "a"}, {2: "b"}, {3: "c"}]

Unlike map , reduce may not be used as a 1-1 mapping. map不同, reduce不能用作1-1映射。 You have full control over the items you want to include or exclude. 您可以完全控制要包含或排除的项目。 Therefore reduce allows you to achieve what filter does, which makes reduce very versatile: 因此, reduce可以让你实现filter功能,这使得reduce非常通用:

[{ a: 1},{ b: 2},{ c: 3}].reduce(function(result, item, index) {if(index !== 0) { //skip the first itemresult.push(item);}return result;
}, []); //an empty array

will produce: [{2: "b"}, {3: "c"}] 将产生: [{2: "b"}, {3: "c"}]

Caution : reduce and Object.key are part of ECMA 5th edition ; 注意reduceObject.keyECMA 5th edition一部分; you should provide a polyfill for browsers that don't support them (notably IE8). 你应该为不支持它们的浏览器提供polyfill(特别是IE8)。

See a default implementation by Mozilla . 请参阅Mozilla的默认实现。


#6楼

Here's a recursive function I just wrote. 这是我刚写的一个递归函数。 It's simple and works well. 这很简单,效果很好。

// Convert array to object
var convArrToObj = function(array){var thisEleObj = new Object();if(typeof array == "object"){for(var i in array){var thisEle = convArrToObj(array[i]);thisEleObj[i] = thisEle;}}else {thisEleObj = array;}return thisEleObj;
}

Here's an example ( jsFiddle ): 这是一个例子( jsFiddle ):

var array = new Array();
array.a = 123;
array.b = 234;
array.c = 345;
var array2 = new Array();
array2.a = 321;
array2.b = 432;
array2.c = 543;
var array3 = new Array();
array3.a = 132;
array3.b = 243;
array3.c = 354;
var array4 = new Array();
array4.a = 312;
array4.b = 423;
array4.c = 534;
var array5 = new Array();
array5.a = 112;
array5.b = 223;
array5.c = 334;array.d = array2;
array4.d = array5;
array3.d = array4;
array.e = array3;console.log(array);// Convert array to object
var convArrToObj = function(array){var thisEleObj = new Object();if(typeof array == "object"){for(var i in array){var thisEle = convArrToObj(array[i]);thisEleObj[i] = thisEle;}}else {thisEleObj = array;}return thisEleObj;
}
console.log(convArrToObj(array));

Results: 结果: 递归数组到对象

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/143174.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

js把对象转换成数组

1.把类似数组的对象转换成数组 【1】什么是类似数组的对象 比如: let arrayLike {0:"z",1:"y",2:"k",length:3 }; 本质是有length属性,可以类似数组的获取元素的方式arrayLike[0]、arrayLike[1]去获取元素&#xff0…

js数组转对象

js数组转对象 1.js var list {}; var arr ["123","456","789"]; for (var key in arr) {list[key] arr[key]; } console.log(list); 效果:

JS 中的类数组对象如何转换为数组?

大家好,我是前端西瓜哥,今天说一下 JS 的类数组对象是什么,以及如何将类数组对象转为数组。 类数组对象是什么? 类数组对象,就是含有 length 属性的对象,但这个对象不是数组。 通常来说还会有 0 &#x…

js中对象转数组

今天睡前看到小组群里贴了这么一张图,印象中曾经面试的时候好像也是遇到过,对于大佬们来说这肯定是很基础的一道题,在此分享给正在学习前端和正在面试的小伙伴们。 这里我用fo……in……实现了两种取值方式的改变 let obj {json:0,production…

(十六)创建Lua脚本模板

Unity里能创建 c#脚本模板,但是如果我想创建Lua脚本模板怎么办呢?拓展一下编辑器吧。 设置一下Lua脚本的模板地址 : Assets/Editor/Lua/Template/lua.lua using UnityEngine; using UnityEditor; using System; using System.IO; using Sys…

Unity(二十):创建自定义脚本模板

编辑器内部自定义脚本存储位置展示 创建自己的自定义脚本 using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEditor.ProjectWindowCallback; using UnityEngine;internal class C…

修改Visual Studio中C#中的默认脚本模板方法

目录 一、修改后的效果 二、修改Visual Studio中C#的默认脚本步骤 三、验证修改模板是否成功 一、修改后的效果 二、修改Visual Studio中C#的默认脚本步骤 ①如果按照Visual Studio的默认安装路径安装该IDE,则路径为: C:\Program Files (x86)\Microsoft Visual …

Unity 添加,修改默认创建脚本模板

Unity 默认创建的脚本可以添加也可以修改,不需要修改Editor。 一、找到模板目录 \Editor\Data\Resources\ScriptTemplates 二、如果要修改模板,直接打开修改就可以了,每个模板都是可以修改的。 修改默认unity创建的脚本: 三、如…

Unity编辑器VS的脚本模板(Script Templates)设置

最近在用Unity做小游戏玩儿时,经常需要用到添加一些整体的说明或者相关系列脚本开发的功能,每一次都需要去手动的敲一下题头说明,虽然也只是从一个脚本copy题头过来修改,但是也是挺麻烦的,做的只是无用功重复&#xff…

unity修改脚本模板

文章目录 前言 前言 在unity有时候创建脚本的时候,会频繁加一些命名空间或者要继承基类并且重写方法,在这里记录一下,修改一下创建脚本时默认模板。 打开安装的unity, 将 81-C# Script-NewBehaviourScript.cs 移动到桌面 使用VS打…

Unity 自定义脚本模板

找到模板 C:\Program Files\Unity\Editor\Data\Resources\ScriptTemplates修改模板 将自己想要自定义模板的原版复制一个副本,并自定义名称 80:序号;Tmz Script:一级列表中的名称;NewTmzScript:新建出来…

pygame安装成功了但却无法导入求大神解

setting里面也设置成功使用了 就是无法导入 有懂得大神指导一下吗 2.8 后面发现是版本不兼容导致的

Pygame下载和安装

Pygame 的下载非常简单,可分为两种方式:一是通过 Python 的包管理器 pip 来安装;二是下载二进制安装包进行安装。其中使用 pip 包管理器安装是最简单、最轻量级的方法,下面以 Windows 系统为例对上述两种方式进行讲解。 图1&#…

pip install pygame安装报错解决方案

针对pip install pygame安装报错的两种不同的解决方法: 一:若python中已经安装好了pip,但pip install pygame却报错的话,可以尝试以下步骤: (1)开始,输入cmd (2&#…

Pygame安装心得

Pygame安装 想必很多人都是从《Python编程:从入门到实践》来的,第一次安装Pygame,我也一样。现在我来谈谈我的安装心得。我的系统是win10。 打开CMD 键盘winR打开运行界面,输入cmd,回车。 (这个黑东西…

pygame的安装

默认python和pip已经安装好了 1、去官网下载pygame 我使用的是py3.8,所以选择cp38。里面包括ios、linux和windows,注意选择64/32位。 2、将pygame复制到项目所在的文件夹中,如图: 3、单击选中include文件夹,按住shi…

python安装pygame教程_python-pygame安装教程

安装好python后,配置环境变量。 安装pygame需要先配置两个环境变量。 第一个是python的。先打开计算机,然后点击‘系统属性’然后点击‘高级系统设置’然后点击‘环境变量’在系统变量中找到path选择并编辑在末尾添加“;”号来作为与前面的间隔。我将p…

pygame 安装方法

本人python初学者,在各种找教程和尝试之后整理pygame 安装方法 说明: 使用系统:Windows 10 64位 python 版本:python 3.8 python安装位置:G:\Python38 以上信息请根据你所使用的电脑有所区别 查询升级pip 版本 pip l…

Pygame 安装教程

实验周用 Python 写个小游戏,需要用到 Pygame ,记录一下安装过程。 一、下载文件 先去官网下载文件。我选的是 Pygame1.9 版本,因为去图书馆借了本书,是按照 Pygame1.9 版本进行讲解的,如果用 Pygame2.X ,…