如何在不更改 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; } </style> </head> <body> <h1>Change an object Key without changing the original array</h1> <button class="Btn">CLICK HERE</button> <h3> Click the above button to change the name object key to fullName </h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let obj = [ { name: "Rohan Sharma", age: 12 }, { name: "Shawn Mendes", age: 18 }, { name: "Michael Shaw", age: 15 }, { name: "Mitch Johansson", age: 19 }, ]; BtnEle.addEventListener("click", () => { obj = obj.map((ele) => { ele["fullName"] = ele["name"]; delete ele["name"]; return ele; }); console.log(obj); }); </script> </body> </html>
输出
以上代码将产生以下输出 −
单击“点击此处”按钮并在控制台中检查输出 −
广告