What is the best way to filter an object this way in ES6?
Starting data:
const acceptedValues = ["value1","value3"]
const myObject = {
prop1:"value1",
prop2:"value2",
prop3:"value3"
}
Expected output:
filteredObject = {
prop1:"value1",
prop3:"value3"
}
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.
ES6 | Array filter() Method Callback: The function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments: element: The current element being processed in the array.
You can use reduce()
to create new object and includes()
to check if value of object exists in array.
const acceptedValues = ["value1", "value3"]
const myObject = {
prop1: "value1",
prop2: "value2",
prop3: "value3"
}
var filteredObject = Object.keys(myObject).reduce(function(r, e) {
if (acceptedValues.includes(myObject[e])) r[e] = myObject[e]
return r;
}, {})
console.log(filteredObject)
For ES6 and if you need static code (you know exactly, what properties you need to filter) and it does not depends on the app state, than you can use the following destructuring technique:
const myObject = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3'
}
const { prop2, ...filteredObject } = myObject
console.info({ filteredObject, prop2 })
And you will have:
filteredObject: {prop1: "value1", prop3: "value3"}
prop2: "value2"
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