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

How to preserve object keys in lodash filter

我有一个数组

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>

看起来你需要这样做很奇怪,但你可以使用 fromEntries 和 entries 来做到这一点

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

console.log(result);

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

如果你只想要新对象中的那个属性,直接抓取它:

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