將數組轉換為JavaScript中的對象

Let's say you have the following array,

假設您有以下數組,

const nums = [1, 2, 3, 4, 5];
console.log(nums);

Output

輸出量

(5) [1, 2, 3, 4, 5]

We know that nums is an array and we can see in the output that we get an array. Let's convert it into an object,

我們知道nums是一個數組,我們可以在輸出中看到得到一個數組。 讓我們將其轉換為對象

console.log(Object.assign({}, nums));

Output

輸出量

{0: 1, 1: 2, 2: 3, 3: 4, 4: 5}

Now we get an object displayed on the console!

現在,我們在控制臺上顯示了一個對象!

Let's see how the Object.assign() method works? The Object.assign() method is built on top of the object class and it takes in two parameters; the target and the source respectively. It copies all values from the source to the target. Let's see some more examples,

讓我們看看Object.assign()方法如何工作? Object.assign()方法建立在對象類的頂部,它具有兩個參數: 目標和源。 它將所有值從源復制到目標。 讓我們再看一些例子

const arr=[
{name:'harry', age:14},
{name:'sam', age:40},
{name:'gloria', age:16},
{name:'riky', age:33},
]
console.log(arr);

Output

輸出量

	(4) [{…}, {…}, {…}, {…}]
0: {name: "harry", age: 14}
1: {name: "sam", age: 40}
2: {name: "gloria", age: 16}
3: {name: "riky", age: 33}
length: 4
__proto__: Array(0)

We have an arr array that contains objects as individual elements. In essence, we have an array of objects. We'll use the object.assign() method to convert this array of objects into an object of objects.

我們有一個arr數組,其中包含對象作為單個元素。 本質上,我們有一個對象數組。 我們將使用object.assign()方法將該對象數組轉換為對象對象。

const namesObj = Object.assign({}, arr);
console.log(namesObj);

Output

輸出量

	{0: {…}, 1: {…}, 2: {…}, 3: {…}}
0: {name: "harry", age: 14}
1: {name: "sam", age: 40}
2: {name: "gloria", age: 16}
3: {name: "riky", age: 33}
__proto__: Object

Now we get back an object of objects! It's pretty simple to use Object.assign() for these types of conversions but it's more important to understand what's going on and how under the hood. Can you think of the internal difference between an array and an object? Now, can you figure out how to write a function that takes in an object and converts it to an array?

現在我們取回對象的對象! 對于這些類型的轉換,使用Object.assign()非常簡單,但更重要的是要了解發生了什么以及如何進行內幕。 您能想到數組和對象之間的內部差異嗎? 現在,您能找出如何編寫一個將一個對象接收并轉換為數組的函數的方法嗎?

Let's see how we'll implement our function that is capable of converting an array to an object. We need two things- a key and a value. Let's assume that we will send across the key as a parameter to our function which we will use as the key for our new object.

讓我們看看如何實現將數組轉換為對象的函數 。 我們需要兩件事-密鑰和值。 假設我們將鍵作為參數傳遞給函數,并將其用作新對象的鍵。

const convertArrtoObj = (arr, key) => {
};

Now we'll create an empty object which we'll fill with elements from our array. We'll use the reduce() method to traverse through the array and put the current value against a key.

現在,我們將創建一個空對象,該對象將填充數組中的元素。 我們將使用reduce()方法遍歷數組并將當前值放在鍵上。

const convertArrtoObj=(arr,key)=>{
const initObj={};
return arr.reduce((obj,currVal)=>{
return{
...obj,
[currVal[key]]:currVal
}
},initObj);
};
const newnamesObj=convertArrtoObj(arr,'age');
console.log(newnamesObj);

Output

輸出量

	{14: {…}, 16: {…}, 33: {…}, 40: {…}}
14: {name: "harry", age: 14}
16: {name: "gloria", age: 16}
33: {name: "riky", age: 33}
40: {name: "sam", age: 40}
__proto__: Object

We converted our original names array to an object using the age of each person as the key.

我們使用每個人的年齡作為鍵將原始名稱數組轉換為對象。

翻譯自: https://www.includehelp.com/code-snippets/convert-an-array-to-an-object-in-javascript.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/541909.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/541909.shtml
英文地址,請注明出處:http://en.pswp.cn/news/541909.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

docker集群運行在calico網絡上

2019獨角獸企業重金招聘Python工程師標準>>> ##網絡及版本信息 docker1 centos7 192.168.75.200 docker2 centos7 192.168.75.201 物理網絡 192.168.75.1/24 Docker version 1.10.3, build 3999ccb-unsupported ,安裝過程略 # calicoctl version Version…

python批量雷達圖_python批量制作雷達圖

老板要畫雷達圖,但是數據好多組怎么辦?不能一個一個點excel去畫吧,那么可以利用python進行批量制作,得到樣式如下:首先制作一個演示的excel,評分為excel隨機數生成:1 INT((RAND()4)*10)/10加入標…

JavaScript中帶有示例的Math.log()方法

JavaScript | Math.log()方法 (JavaScript | Math.log() Method) Math.log() is a function in math library of JavaScript that is used to return the value of natural Log i.e. (base e) of the given number. It is also known as ln(x) in mathematical terms. Math.log…

SUI踩坑記錄

SUI踩坑記錄 最近做了個項目選型了SUI和vue做單頁應用。下面記錄一下踩坑經歷SUI 介紹 sui文檔:http://m.sui.taobao.org/SUI Mobile 是一套基于 Framework7 開發的UI庫。它非常輕量、精美,只需要引入我們的CDN文件就可以使用,并且能兼容到 i…

java 寫入xml文件_java讀寫xml文件

要讀的xml文件李華姓名>14年齡>學生>張三姓名>16年齡>學生>學生花名冊>package xml;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.Iterator;import java.util.Vector;import javax.xml.pa…

JavaScript中帶有示例的Math.max()方法

JavaScript | Math.max()方法 (JavaScript | Math.max() Method) Math.max() is a function in math library of JavaScript that is used to return the greatest value of all the passed values to the method. Math.max()是JavaScript數學庫中的函數,用于將所有…

java 修飾符默認_Java和C#默認訪問修飾符

C#中:針對下面幾種類型內部成員的訪問修飾符:enum的默認訪問修飾符:public。class的默認為private。interface默認為public。struct默認為private。其中:public可以被任意存取;protected只可以被本類和其繼承子類存取&…

JavaScript中帶有示例的Math.abs()方法

JavaScript | Math.abs()方法 (JavaScript | Math.abs() Method) Math operations in JavaScript are handled using functions of math library in JavaScript. In this tutorial on Math.abs() method, we will learn about the abs() method and its working with examples.…

人臉識別python face_recognize_python2.7使用face_recognition做人臉識別

偶然看到一篇文章,說是可以實時人臉識別,很有興趣就自己按照文章開始動手人臉識別,但是實現過程中遇到了幾個問題這里做個總結,希望可以幫助到大家安裝face_recognition這個之前需要先安裝編譯dlib,如果沒有安裝dlib&a…

c# reverse_清單 .Reverse()方法,以C#為例

c# reverseC&#xff03;List <T> .Reverse()方法 (C# List<T>.Reverse() Method) List<T>.Reverse() method is used to reverse the all list elements. List <T> .Reverse()方法用于反轉所有列表元素。 Syntax: 句法&#xff1a; void List<T&…

cpuinfo詳解

cat /proc/cpuinfo processor: 23&#xff1a;超線程技術的虛擬邏輯核第24個 ###一般看最后一個0...23 表示24線程 vendor_id: GenuineIntel&#xff1a;CPU制造商cpu family: 6&#xff1a;CPU產品系列代號model: 44&#xff1a;CPU屬于其系列中的哪一代號model name: Intel…

jvm延遲偏向_用于偏向硬幣翻轉模擬的Python程序

jvm延遲偏向Here, we will be simulating the occurrence coin face i.e. H - HEAD, T - TAIL. Simply we are going to use an inbuilt library called as random to call a random value from given set and thereby we can stimulate the occurrence value by storing the o…

java項目沒有bin_WebAPI項目似乎沒有將轉換后的web.config發布到bin文件夾?

我很擅長.NET配置轉換 . 我現在將它們放在用于數據使用的類庫和WPF應用程序上 .但是&#xff0c;當我嘗試使用ASP.NET WebAPI項目進行設置時&#xff0c;似乎發生了一些奇怪的事情 .配置文件永遠不會顯示在我的bin目錄中&#xff0c;因此web.config始終顯示為預先形成的配置文件…

opengl es的射線拾取

2019獨角獸企業重金招聘Python工程師標準>>> 在opengl中關于拾取有封裝好的選擇模式&#xff0c;名字棧&#xff0c;命中記錄&#xff0c;實現拾取的功能&#xff0c;相對容易一些。但是到了opengl es里面就比較倒霉了&#xff0c;因為opengl es是opengl的簡化版&am…

java timezone_Java TimeZone useDaylightTime()方法與示例

java timezoneTimeZone類useDaylightTime()方法 (TimeZone Class useDaylightTime() method) useDaylightTime() method is available in java.util package. useDaylightTime()方法在java.util包中可用。 useDaylightTime() method is used to check whether this time zone u…

視覺學習(4) —— 添加地址傳遞數據

Modbus Slave 選擇一個地址右鍵&#xff0c;選擇發送的數據類型 視覺軟件 一、添加地址 當地址為100時&#xff0c;先將首地址改為100&#xff0c;第0個地址為100&#xff0c;第1個地址為101&#xff0c;往后累加 若想使用100—150的地址&#xff0c;即首地址為100&#xff…

某個JAVA類斷點無效_解決eclipse中斷點調試不起作用的問題

最近幾天&#xff0c;遇到了一個問題&#xff0c;就是在eclipse中進行斷點調試程序到時候&#xff0c;跟蹤不到我設置的斷點。困惑了很久&#xff0c;在網上也查閱了很多資料&#xff0c;都沒能解決我的問題。今天早上&#xff0c;我試著把eclipse的工作空間重新換了一個&#…

jquery中阻止事件冒泡的方法

2019獨角獸企業重金招聘Python工程師標準>>> 根據《jquery基礎教程》 第一種方法&#xff1a;判斷事件的“直接”目標是否是自身&#xff0c;如果不是自身&#xff0c;不予處理 $(div.outter).click(function(event) {if (event.target this) {$(p).css(color, red…

java swing 組織機構_課內資源 - 基于Java Swing的小型社團成員管理系統

一、需求分析1.1 個人信息學號、姓名、性別、年級、系別、專業、出生日期、聯系方式、個性簽名、地址、照片。1.2 基本功能要求管理員信息管理登錄、注銷功能修改密碼功能部落成員信息管理添加成員刪除成員修改成員信息按條件查找篩選成員1.3 高級特性管理員權限管理成員信息包…