Skip to content
Advertisement

How to preserve object keys in lodash filter

I have an array

const sampleObject = {Color: "Blue", Size: "39, 41"}

Using Lodash’s _.filter when I try

_.filter(sampleObject, (entry) => entry !== 'Blue')

I get

['39, 41']

But my desired result is

{Size: '39, 41'}

const sampleObject = {
  Color: "Blue",
  Size: "39, 41"
}
const filtered = _.filter(sampleObject, (entry) => entry !== 'Blue')
console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

Advertisement

Answer

Are you looking for _.pickBy()?

const sampleObject = {
  Color: "Blue",
  Size: "39, 41"
}
const filtered = _.pickBy(sampleObject, (value,key) => value !== 'Blue')
console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
Advertisement