Say I have an object like this:
var things = {
"First Item": {"name": "First Item", "url":"firstitem" },
"Second Item": {"name": "Second Item", "url":"seconditem" }
};
I want to be able to check if any of the object values have a url value of "firstitem", and if so, retrieve all of the values associated with that item (for "name" and "url"). How would one go about making a loop to accomplish this?
var things = {
"First Item": {"name": "First Item", "url":"firstitem" },
"Second Item": {"name": "Second Item", "url":"seconditem" }
};
Object.keys(things).
filter(k => things[k].url === "firstitem").
map(k => things[k])
// [ { name: 'First Item', url: 'firstitem' } ]
There are 2 ways to loop over this. You can use the foreach method:
for (var key in things) {
things[key].url; // do thing with this
}
Or the Object.keys method
Object.keys(things); // Returns an array of ["First Item", "Second Item"]
I prefer the second, because for your use case you can do this:
Object.keys(things).find(elem => things[elem].url === "seconditem");
This will return undefined
if it isn't found, or in the case above, it will return {"name": "Second Item", "url": "seconditem" }
You can also use findIndex in place of find, which will get you the index of it in the array returned by Object.keys()
For more details:
Object.keys()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys Array.prototype.find()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find Array.prototype.findIndex()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.