Home > Back-end >  FIlter a dictionary array in JavaScript
FIlter a dictionary array in JavaScript

Time:08-26

I'm using a feth request to recieve data from an API. This is what my request looks like:

fetch(url, requestOptions)
.then(response => response.json())
.catch(error => colsole.log('error', error);

And I'm trying to figure out how to filter certain values from the response. Here's what the response looks like:

[
  {
    'Obj.Name': 'objname1',
    'Obj.property': 'red'
    ...
  },
  {
    'Obj.Name': 'objname1',
    'Obj.property': 'blue'
    ...
  },
  {
    'Obj.Name': 'objname3',
    'Obj.property': 'green'
    ...
  },
]

I wanna add another ".then" statement there with a function that gets a parameter like ('Obj.Name') that can filter everything by that particular objectname and be able to get other properties of that object. I want the result to be something like this:

Obj: objectname1, ObjProp: red

CodePudding user response:

Like this?

fetch(url, requestOptions)
.then(response => response.json())
.then((data) => {
  const filtered = data.filter(item => item["Obj.Name"] === "objname1")
  console.log(filtered)
})
.catch(error => colsole.log('error', error);

  • Related