如何通过循环查找JavaScript对象中指定url属性的元素并获取其信息?
How to Loop Through a JavaScript Object to Find an Item by URL Property
Hey there! Let's walk through how to loop through your things object to find the item with a url value of "firstitem" and grab its name and url properties.
First, let's recap your original object for reference:
var things = { "First Item": {"name": "First Item", "url":"firstitem" }, "Second Item": {"name": "Second Item", "url":"seconditem" } };
Method 1: Using for...in Loop (Traditional Object Traversal)
This is a classic way to iterate over an object's keys. We'll check each key's corresponding value for the target url:
for (const key in things) { // Always add this check to avoid iterating over prototype properties if (things.hasOwnProperty(key)) { const currentItem = things[key]; // Check if the current item's url matches our target if (currentItem.url === "firstitem") { // Extract name and url using destructuring (cleaner syntax!) const { name, url } = currentItem; console.log(`Found the item: Name = ${name}, URL = ${url}`); // If you only need the first match, add a break to stop looping early break; } } }
Method 2: Using Object.values() + for...of Loop
Object.values() gives us an array of all the object's values, which makes iteration more straightforward since we don't need to deal with keys:
// Get an array of all the items in the things object const items = Object.values(things); for (const item of items) { if (item.url === "firstitem") { const { name, url } = item; console.log(`Found match: Name - ${name}, URL - ${url}`); break; // Stop searching once we find the first match } }
Method 3: Using Array.prototype.some() (For Early Termination)
If your goal is to find the first matching item and stop immediately, some() is perfect—it stops iterating as soon as it hits a return true:
Object.values(things).some(item => { if (item.url === "firstitem") { const { name, url } = item; console.log(`Found the item: Name = ${name}, URL = ${url}`); return true; // This tells some() to stop looping } return false; });
Quick Notes:
- If you need to find all items with the target
url(in case there are multiple), just remove thebreakstatement (or skipsome()and useforEachinstead). - Using object destructuring (
const { name, url } = item) is optional but makes the code cleaner than accessing properties withitem.nameanditem.url.
内容的提问来源于stack exchange,提问作者user4671351
相关产品推荐
相关产品推荐

