简体   繁体   English

如何在 lodash 过滤器中保留对象键

[英]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当我尝试时使用 Lodash 的 _.filter

_.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() ?你在找_.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您需要执行此操作似乎很奇怪,但是您可以使用 fromEntries 和条目来执行此操作

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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