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) ?

1

2 Answers 2

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; 
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very very much! Because I need the index of the element anyway (to focus this element) I used $.inArray now :)
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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.