0

I have an object with the following structure:

data = 
{
  columns: array of objects,
  rows: [
    {
      id: 1,
      process: "A",
      status: "ok"
    },
    {
      id: 2,
      process: "A",
      status: "ko"
    },
    {
      id: 3,
      process: "B",
      status: "ok"
    },
    ...
  ]
}

I then want to create another object that has the same column values, but in the rows field I want to put only the objects that have process === "A".

I've come up with this so far, that I think it's fine:

const filteredData = {
    "columns": data.columns,
    "rows": selectedProcess !== '' ? data.rows.filter(r => r.process === selectedProcess) : []
  }

My question is if there is another way to make this in a more clever way.

mattiatantardini
  • 525
  • 1
  • 5
  • 23
  • That warning seems to be specific to React. – Barmar May 13 '22 at 15:08
  • Related, maybe duplicate: https://stackoverflow.com/questions/70988956/eslint-to-fix-this-wrap-the-initialization-of-constant-in-its-own-usememo – Barmar May 13 '22 at 15:09
  • Yeah, I noted the linked answer and I'm following it to avoid the React warning, thank you. Maybe I can leave out this from the question. The point is if there is a general way to filter an object in the way I want – mattiatantardini May 13 '22 at 15:11
  • Your filtering method looks fine to me. – Barmar May 13 '22 at 15:14
  • I don't think you need the ternary. If `selectedProcess` is empty, it won't match anything, so you'll get an empty result automatically. – Barmar May 13 '22 at 15:15
  • If the code works and you're looking for advice on improving it, [codereview.se] is the appropriate place. But see https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users first. – Barmar May 13 '22 at 15:15
  • Does this answer your question? [Get JavaScript object from array of objects by value of property](https://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-of-property) – HerrAlvé May 13 '22 at 16:08
  • Thanks @AlveMonke, your link answers my question related to the filtering of `rows` keyword. My goal was also to keep the 'columns` keyword as in the original object and filter the `rows` keyword. – mattiatantardini May 15 '22 at 14:50

1 Answers1

0

You can check out the solution Below:

const filteredData = {
    "columns": data.columns,
    "rows": data.rows.filter(item=>item.process==='A')
  }
Mundruku
  • 229
  • 4
  • 5