1

i have a problem with the following situation:

I have an Array of Objects which all contains the same attribute, which is called src

Before adding a new Object (with an src attribute too), I want to check if the value already exists in just one src attribute in the Objects Array.

Therefore I wanted to use $.inArray() with the new src as first parameter and as array not the array of objects, but the array of the values of the attributes from the objects array.

As Example:

I have

var arrayOfObjects = [{
    src : "source1",
    otherAttribute : "value"
}, {
    src : "source2",
    otherAttribute : "value"
}];

My question is: Is there a build in function in JavaScript/jQuery which returns

["source1","source2"]

when called with functionX(arrayOfObjects) ?

Ba5t14n
  • 719
  • 2
  • 5
  • 20
  • possible duplicate of [How can I convert the "arguments" object to an array in JavaScript?](http://stackoverflow.com/questions/960866/how-can-i-convert-the-arguments-object-to-an-array-in-javascript) – Stratus3D Jan 08 '15 at 15:21

2 Answers2

2

Well, you can always use Array.prototype.map():

var sources = arrayOfObjects.map(function(obj) {
  return obj.src;
});

... but for your specific case, I'd rather choose a bit different approach - checking against array directly with Array.prototype.some():

function doesSourceExist(source) {
  return arrayOfObjects.some(function(obj) { 
    return obj.src === source; 
  });
}
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 1
    Thank you very very much! Because I need the index of the element anyway (to focus this element) I used `$.inArray` now :) – Ba5t14n Jan 08 '15 at 15:35
0

Not an answer but an addendum to @raina77ow's answer for cleaner code.

function property(prop) {
  return function(obj) {
    return obj[prop];
  };
}

var sources = arrayOfObjects.map(property('src'));
Sukima
  • 9,965
  • 3
  • 46
  • 60