दो सरणियों को एक 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; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Convert two arrays into one JavaScript object</h1> <div class="sample"> ["firstName", "lastName", "age"]<br />["Rohan", "Sharma", 21] </div> <div class="result"><br /></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to create an object from the above two arrays</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); var objKeys = ["firstName", "lastName", "age"]; var objValues = ["Rohan", "Sharma", 21]; var resultObj = {}; BtnEle.addEventListener("click", () => { objKeys.forEach( (element, index) => (resultObj[element] = objValues[index]) ); for (let i in resultObj) { resEle.innerHTML += "Key = " + i + " : Value = " + resultObj[i] + "<br>"; } }); </script> </body> </html>
आउटपुट
उपरोक्त कोड निम्न आउटपुट उत्पन्न करेगा -
'यहां क्लिक करें' बटन पर क्लिक करने पर -