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}];
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With