Home > Blockchain >  how can i check if an array of objects contains a key which is in array of strings js?
how can i check if an array of objects contains a key which is in array of strings js?

Time:01-31

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? 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. we should remove key with value as well.

CodePudding user response:

It's simple and no need for any nested cycles. There are two option to do that

  1. Using includes function
    const result = arr.filter((item) => !result.includes(item.id));
  1. Using 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.

CodePudding user response:

Since you stated that it could be implemented using lodash... here code using lodash

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

CodePudding user response:

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