2

I have written a custom callback function for Javascript's find function but that is always yielding undefined

var objectsArray = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 41, 'b': 5, 'c': 7 },
  { 'a': 9, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 99 }
];

function mytestMatchesProp(inputKey,val){
    let matchFunc = function(element,index,array){
      Object.keys(element).every(function(key){
          let val1 = (key==inputKey) && (element[key] == val)
          return val1
      })
    }
    return matchFunc
}

let res = objectsArray.find(mytestMatchesProp('a',9))
 console.log('output',res)

I have added a running snippet, any suggestion would be helpful. Maybe i am missing something minor

2 Answers 2

4

You could just return the function for the callback with the right check without key iteration.

var objectsArray = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 41, 'b': 5, 'c': 7 },
  { 'a': 9, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 99 }
];

function mytestMatchesProp(inputKey, val){
    return function(element, index, array){
        return inputKey in element && element[inputKey] === val;
    };
}

let res = objectsArray.find(mytestMatchesProp('a', 9));
console.log('output', res);

Sign up to request clarification or add additional context in comments.

Comments

2

You need to change every to some for first, because the every will always return false and also return the result of Object.keys(element).some.... And can simplify.

But I can suggest you more simple code, you only need to check if the property is in the object and it's value is the val, with using lambdas

var objectsArray = [
  { 'a': 1, 'b': 2, 'c': 3 },
  { 'a': 41, 'b': 5, 'c': 7 },
  { 'a': 9, 'b': 2, 'c': 3 },
  { 'a': 4, 'b': 5, 'c': 99 }
];

function mytestMatchesProp(inputKey,val){
    return (element,index,array) => inputKey in element && element[inputKey] === val;
}

let res = objectsArray.find(mytestMatchesProp('a',9))
 console.log('output',res)

1 Comment

Thanks for the explanation

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.