如何將字典轉換成 JavaScript 物件列表?
以下是將字典轉換為 JavaScript 物件列表的程式碼 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample{
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
</style>
</head>
<body>
<h1>Convert dictionary into list of JavaScript objects</h1>
<div class="sample">
{ A: { 1: "Apple", 2: "Apricot" }, B: { 1: "Ball", 2: "Bull" }, C: { 1:
"Cat", 2: "Cow" }, D: { 1: "Dog", 2: "Drill" }, }
</div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to convert the above dictionary into list of object</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let arr;
const obj = {
A: { 1: "Apple", 2: "Apricot" },
B: { 1: "Ball", 2: "Bull" },
C: { 1: "Cat", 2: "Cow" },
D: { 1: "Dog", 2: "Drill" },
};
BtnEle.addEventListener("click", () => {
arr = Object.values(obj);
console.log(arr);
});
</script>
</body>
</html>輸出
以上程式碼將生成以下輸出 −

單擊“點選此處”按鈕,並在控制檯中檢視輸出 −

Advertisement
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP