如何将字典转换成 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>

输出

以上代码将生成以下输出 −

单击“点击此处”按钮,并在控制台中查看输出 −

更新于:18-Jul-2020

1K+ 次浏览

开启您的 职业道路

完成课程,获得认证

开始学习
Advertisement