screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head></head> <body> <h3>Javascript find object in array by id</h3> <p id="result"></p> <button onclick="findObjectById(2)">Click me to Find Object</button> <script> function findObjectById(targetId) { const demoArray = [ { id: 1, name: "John" }, { id: 2, name: "Jane" }, { id: 3, name: "Bob" }, ]; const foundObject = demoArray.find((obj) => obj.id === targetId); if (foundObject) { const resultElement = document.getElementById("result"); resultElement.textContent = `Found object: ${JSON.stringify(foundObject)}`; // Stringify the object } else { const resultElement = document.getElementById("result"); resultElement.textContent = "Object not found"; } } </script> </body> </html>