【问题标题】:How to preserve object keys in lodash filter如何在 lodash 过滤器中保留对象键
【发布时间】:2021-07-23 17:10:41
【问题描述】:

我有一个数组

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

尝试使用 Lodash 的 _.filter

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

我明白了

['39, 41']

但我想要的结果是

{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>

【问题讨论】:

  • Color 不是"Blue" 时,您试图省略对象属性Color?您是在过滤单个对象还是过滤一组对象?您在应用程序中实际在做什么?
  • 那不是数组,是对象。

标签: javascript reactjs lodash


【解决方案1】:

你在找_.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>

【讨论】:

    【解决方案2】:

    您需要这样做似乎很奇怪,但您可以使用 fromEntries 和 entries 来执行此操作

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

    【讨论】:

      【解决方案3】:

      如果您只想要新对象中的一个属性,请直接获取它:

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

      或者如果您需要动态密钥:

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

      【讨论】:

        猜你喜欢
        • 2016-05-24
        • 2020-01-23
        • 2015-08-23
        • 2016-03-23
        • 2022-01-18
        • 2013-06-10
        • 1970-01-01
        • 2023-01-25
        相关资源
        最近更新 更多