Sai
Sai

Reputation: 2022

Filter object array via nodejs

I have an object array which look something like below,

{
  "data": [
            {
              "name": "HTML",
              "description": "Hyper Text Markup Language"
            },
            {
              "name": "CSS",
              "description": "Cascading Style Sheet"
            },
            {
              "name": "JS",
              "description": "Javascript"
            }
          ]
}

I get the above object array as a response from this end point /get/technologies, suppose if this end point is gonna have a query string some thing like this /get/technologies?q=CSS how can i filter the response just to render the below,

{
  "data": [
            {
              "name": "CSS",
              "description": "Cascading Style Sheet"
            }
          ]
}

I have a node/express app so in the controller if i do "req.query.q" then i can grab the query parameter, with that query parameter how can i filter the original object array.. i came across some npm packages but not sure which would suite my need,

https://www.npmjs.com/package/filter-array
https://www.npmjs.com/package/object-filter
https://www.npmjs.com/package/array-filter
https://www.npmjs.com/package/array-query

It would also be nice if i can grab the query parameter and find the matching texts.. say for example if the query parameter is just "SS" then the result should render both CSS and JS since the text "S" is there in both of them.

Upvotes: 0

Views: 7944

Answers (2)

birnbaum
birnbaum

Reputation: 4946

You could just use filter:

var data = [
  // the array to be filtered
];

var filteredArray = data.filter(item => (item.name === req.query.q));

Upvotes: 1

omarjmh
omarjmh

Reputation: 13888

Working Example

Try this:

var d = [
            {
              "name": "HTML",
              "description": "Hyper Text Markup Language"
            },
            {
              "name": "CSS",
              "description": "Cascading Style Sheet"
            },
            {
              "name": "JS",
              "description": "Javascript"
            }
          ];

var a = d.filter(function(el) {
  return el.name === 'CSS';
});

Upvotes: 3

Related Questions