简体   繁体   English

如何检查对象数组是否包含字符串数组中的键 js?

[英]how can i check if an array of objects contains a key which is in array of strings js?

We have an array of objects like我们有一个对象数组,例如

const arr = [{id: "someId", name: {...}}, ...];
const skippedKeys = ["id"...]

How can i filtered the array of object based on skipped keys?如何根据跳过的键过滤 object 的数组? The result should be:结果应该是:

const result = [{name: {...}}, ...];

Also i don't want to make a cycle inside the cycle.我也不想在循环中创建一个循环。 the result also could be implemented using lodash library.结果也可以使用 lodash 库来实现。 we should remove key with value as well.我们也应该删除带有值的键。

It's simple and no need for any nested cycles.这很简单,不需要任何嵌套循环。 There are two option to do that有两种选择可以做到这一点

  1. Using includes function使用includes function
    const result = arr.filter((item) => !result.includes(item.id));
  1. Using set使用set
    const dataSet = new Set(skippedKeys);
    const result = arr.filter((item) => !dataSet.has(item.id));

I prefer the second one as it excludes double checks.我更喜欢第二个,因为它不包括双重检查。 Hope the answer was helpful.希望答案是有帮助的。

const result = arr.map(obj =>
  Object.keys(obj).reduce(
    (res, key) => (
      skippedKeys.includes(key) ? res : {...res, [key]: obj[key]}
    ),
    {},
));

Since you stated that it could be implemented using lodash... here code using lodash既然你说它可以使用 lodash 来实现......这里的代码使用 lodash

 let result = _.map(arr, (el)=> _.omit(el, skippedKeys))

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

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