Object.fromEntries() JavaScript 中的方法。
JavaScript 中的 Object.fromEntries() 方法用于将诸如数组、映射这样具有键值对的可迭代对象转换为对象。
以下是 Object.fromEntries() 方法的代码 −
示例
<!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; } .result,.sample { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>Object.fromEntries() method </h1> <div class="sample"><pre>[[firstName,Rohan],[lastName,Sharma],[age,22]]</pre></div> <div style="color: green;" class="result">Object = <br></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to convert the above array into object</h3> <script> let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let arr = [['firstName','Rohan'],['lastName','Sharma'],['age',22]]; document.querySelector(".Btn").addEventListener("click", () => { let obj = Object.fromEntries(arr); for(i in obj){ resEle.innerHTML += 'Key = '+i+' : Value = '+obj[i]+ '<br>'; } }); </script> </body> </html>
输出
上面的代码将产生以下输出 −
点击“点击此处”按钮 −
广告