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 }]
kevin janada
  • 41
  • 1
  • 2
  • 10
  • 1
    What do you mean by `has all key value pairs`? – Rajesh Feb 24 '17 at 11:13
  • Possible duplicate of [Get JavaScript object from array of objects by value or property](http://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) – Rajesh Feb 24 '17 at 11:14

4 Answers4

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 })) 
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
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>
Atanu Mallick
  • 266
  • 4
  • 7
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 }));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
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 }));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 1
    `pattern[k] = o[k]` this is an asignment, no comparison ;) and I'd remove/extract this part `Object.keys(pattern)` out of the loop – Thomas Feb 24 '17 at 11:21