我遇到以下情况的问题:
我有一个对象数组,它们都包含相同的属性,称为src
在添加新对象(也具有src
属性)之前,我想检查对象数组中的一个src
属性中是否已存在该值。
因此,我希望$.inArray()
使用新src
作为第一个参数,而数组不是对象数组,而是使用对象数组中属性值的数组。
例如:
我有
var arrayOfObjects = [{
src : "source1",
otherAttribute : "value"
}, {
src : "source2",
otherAttribute : "value"
}];
我的问题是:JavaScript / jQuery中是否有一个返回
的函数["source1","source2"]
用functionX(arrayOfObjects)
调用时?
答案 0 :(得分:2)
嗯,您可以随时使用Array.prototype.map():
var sources = arrayOfObjects.map(function(obj) {
return obj.src;
});
...但是对于您的具体情况,我宁愿选择一种不同的方法 - 直接使用Array.prototype.some()检查数组:
function doesSourceExist(source) {
return arrayOfObjects.some(function(obj) {
return obj.src === source;
});
}
答案 1 :(得分:0)
不是答案,而是@ raina77ow对更清洁代码的答案的附录。
function property(prop) {
return function(obj) {
return obj[prop];
};
}
var sources = arrayOfObjects.map(property('src'));