Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an object with its values in ES6

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"
}
like image 889
saawsann Avatar asked May 17 '17 13:05

saawsann


People also ask

How do you filter the value of a object?

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.

Can you filter a JavaScript object?

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.

How can we filter an array of elements from a given array in ES6 *?

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.


2 Answers

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)
like image 107
Nenad Vracar Avatar answered Oct 21 '22 19:10

Nenad Vracar


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"
like image 27
Roman Avatar answered Oct 21 '22 18:10

Roman