如何在一个对象数组中找到一个没有属性'x'的对象? [英] How do I find in an array of objects an object that doesnt have a property 'x'?
问题描述
说我有一个对象数组:
[{name:Chris,年龄:14,loc:kw},{name:Eric,loc:kw }]
如何找到没有属性年龄的对象ieobjects [1]
我尝试了什么:
objects.find(function(el){return element.age === undefined})
你的代码行几乎可以工作,但在你使用的函数element.age
但是元素
中不存在;你调用了参数el
。请尝试el.age
。
我倾向于使用 Object.prototype.hasOwnProperty [ ^ ]确定是否已定义属性:
< pre lang =Javascript> var value = objects.find( function (el){ return !el.hasOwnProperty( age); });
注意: Array.prototype.find [ ^ ]将找到匹配的第一个元素。如果要查找所有匹配的元素,请使用 Array.prototype.filter [ ^相反。
var allValues = objects.filter( function (el){ return !el.hasOwnProperty( age);});
请注意,这两个函数在旧浏览器中的支持有限。有可用的polyfills。
如果你只支持更新的浏览器 - 特别是不 Internet Explorer - 你可能还想考虑使用< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions>箭头功能 [ ^ ]简化代码:
var value = objects.find(el =>!el.hasOwnProperty( age));
var allValues = objects.filter(el =>!el.hasOwnProperty( < span class =code-string> age));
Say I have an array of objects:
[{name:"Chris", age:14, loc:"kw"},{name:"Eric", loc:"kw"}]
How do I find the object without property age i.e.objects[1]
What I have tried:
objects.find(function(el){return element.age===undefined})
Your line of code would almost work, but inside the function you useelement.age
butelement
does not exist; you called your parameterel
. Tryel.age
instead.
I'd be inclined to use Object.prototype.hasOwnProperty[^] to determine whether the property has been defined:
var value = objects.find(function(el){ return !el.hasOwnProperty("age"); });
NB: Array.prototype.find[^] will find the first element which matches. If you want to find all matching elements, use Array.prototype.filter[^] instead.
var allValues = objects.filter(function(el){ return !el.hasOwnProperty("age"); });
Note that both functions have limited support in older browsers. There are polyfills available.
If you're only supporting newer browsers - specifically not Internet Explorer - you might also want to consider using Arrow functions[^] to simplify the code:
var value = objects.find(el => !el.hasOwnProperty("age")); var allValues = objects.filter(el => !el.hasOwnProperty("age"));
这篇关于如何在一个对象数组中找到一个没有属性'x'的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!