0

How do you return objects in an array if it contain specific key-value pairs?

I need to return it if it has all key value pairs given, not just one.

for example,

This function with the array of objects as the 1st argument, and an object with given key value pairs as the 2nd argument

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }); 

should return

[{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]
2

4 Answers 4

1

You can do this with filter() and every().

function whatIsInAName(a, b) {
  return a.filter(function(e) {
    return Object.keys(b).every(function(c) {
      return e[c] == b[c]
    })
  })
}

console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })) 

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

1 Comment

Thanks for the help! appreciate it!
1

Use underscore.js. It's simple.

function whatIsInAName(a, b){
	return _.where(a, b);
}
var data = whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Comments

0

Use Array#filter method with Array#every method.

function whatIsInAName(arr, obj) {
  // get the keys array
  var keys = Object.keys(obj);
  // iterate over the array
  return arr.filter(function(o) {
    // iterate over the key array and check every property
    // is present in the object with the same value 
    return keys.every(function(k) {
      return obj[k] === o[k];
    })
  })
}


console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

1 Comment

Thanks! appreciate your help!
0

You could filter the array with a check for the pattern's key and values.

function whatIsInAName(array, pattern) {
    var keys = Object.keys(pattern);
    return array.filter(function (o) {
        return keys.every(function (k) {
            return pattern[k] === o[k];
        });
    });
}

console.log(whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }));

1 Comment

pattern[k] = o[k] this is an asignment, no comparison ;) and I'd remove/extract this part Object.keys(pattern) out of the loop

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.