1

I have this object that I need to filter it.

let data = JSON.parse(this.getDataFromArray).map((x: any) => x.isEnabled === true);

I need to get in "data" only ID's of values that "isEnabled" is true.

1
  • Hey @ForkExe please try to research a bit more before you ask a new question. Since this is a very simple problem and has been answered too many times before, you could already find solutions by doing a bit more scrolling through the website. Here is one of them that I could find which points the exact issue: stackoverflow.com/questions/31201262/… Commented Dec 9, 2021 at 14:57

2 Answers 2

1

Use Array.prototype.flatMap to achieve the result.

const dataArray = [
  { id: 1, name: "Alice", isEnabled: false },
  { id: 2, name: "Bob", isEnabled: true },
  { id: 3, name: "Charlie", isEnabled: true },
  { id: 4, name: "Dave", isEnabled: true },
  { id: 5, name: "Eve", isEnabled: false },
  { id: 6, name: "Frank", isEnabled: false },
];
let data = dataArray.flatMap(elm => elm.isEnabled ? [elm.id]: []);
console.log(data);

Please note that flatMap cannot be used in IE without a polyfill.

If you need IE support, use Array.prototype.forEach

const dataArray = [
  { id: 1, name: "Alice", isEnabled: false },
  { id: 2, name: "Bob", isEnabled: true },
  { id: 3, name: "Charlie", isEnabled: true },
  { id: 4, name: "Dave", isEnabled: true },
  { id: 5, name: "Eve", isEnabled: false },
  { id: 6, name: "Frank", isEnabled: false },
];
let data = [];
dataArray.forEach((elm) => {
  if (elm.isEnabled) {
    data.push(elm.id);
  }
});
console.log(data);

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

4 Comments

Okey, but I need to store only ID's , not all object
@ForkExe Then filter like this, then map the result to just store the ID's
@ForkExe: Updated the answer to use flatMap
nice never saw flatMap
0

Try this to filter first, and map to desired property:

JSON.parse(this.getDataFromArray).filter((x: any) => x.isEnabled === true).map((result: any) => result.id);

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.