简体   繁体   中英

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>

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>

Seems odd you need to do this, but you can use fromEntries and entries to do it

 const sampleObject = {Color: "Blue", Size: "39, 41"} const result = Object.fromEntries(Object.entries(sampleObject).filter(x => x[1] !== 'Blue')); console.log(result);

If you want just that one property in a new object, grab it directly:

 const sampleObject = {Color: "Blue", Size: "39, 41"}; const result = {Size: sampleObject.Size}; console.log(result);

Or if you need the key to be dynamic:

 const sampleObject = {Color: "Blue", Size: "39, 41"}; const key = "Size"; const result = {[key]: sampleObject[key]}; console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM