[英]Finding a item in a javascript object based on an item's properties
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"). 我希望能够检查是否任何对象值的URL值均为“ firstitem”,如果是,则检索与该项目关联的所有值(“名称”和“ 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:
您可以使用foreach方法:
for (var key in things) {
things[key].url; // do thing with this
}
Or the Object.keys method 或Object.keys方法
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" }
如果找不到,将返回
undefined
,或者在上述情况下,它将返回{"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()
您也可以使用findIndex代替find,这将使您在
Object.keys()
返回的数组中获得索引。
For more details: 更多细节:
Object.keys()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys Object.keys()
https://developer.mozilla.org/zh-CN/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.find()
https://developer.mozilla.org/zh-CN/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 Array.prototype.findIndex()
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.