Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching key/value pair from one object to another in JavaScript

Tags:

javascript

If I have an array of objects and one object in JavaScript:

var data = [{"a": 1, "b": 2}, {"a": 1}, {"a": 1, "b": 2, "c": 3}];
var myFilter = {"a": 1, "b": 2};

...and would like to use myFilter object as a filter to the array of objects to create a new array of objects if and only if the object at least matches or contain the myFilter key/value pairs.

Any recommendation how can I go ahead and put it into code? I need to create a new array that was filtered from data using the myFilter key/value pair.

I was able to do this but myFilter only contains 1 key/value pair.

My expected new array is:

var newArr = [];
newArr = [{"a": 1, "b": 2}, {"a": 1, "b": 2, "c": 3}];
like image 553
arantebw Avatar asked Jan 06 '23 22:01

arantebw


1 Answers

You can use arr.filter(callback[, thisArg]) for this:

var data = [{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 3 }]
var myFilter = { "a": 1, "b": 2 }

var myFilterFunction = function(obj) {
  for (var p in myFilter) {
    if (obj[p] !== myFilter[p]) return false
  }
  return true
}

var newArr = data.filter(myFilterFunction)

document.write(JSON.stringify(newArr))

A more universal approach would be this filterFuncByObj(filterObj) function, wich takes any custom filter object:

data.filter(filterFuncByObj(myFilter)):

var data = [{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 3 }]
var myFilter = { "a": 1, "b": 2 }

var newArr = data.filter(filterFuncByObj(myFilter))

// Demo Output
document.write(JSON.stringify(newArr))


function filterFuncByObj(filterObj) {
  return function(obj) {
    for (var p in filterObj) {
      if (obj[p] !== filterObj[p]) return false
    }
    return true
  }
}
like image 173
CoderPi Avatar answered Jan 09 '23 18:01

CoderPi