0

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.

3 Answers 3

3

Since you stated that it could be implemented using lodash, here is some code using lodash:

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

thanks for your suggestion. but we should remove key with value as well. i will add this to the description also
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.