Home > Software design >  How would I search a JSON array in nodejs
How would I search a JSON array in nodejs

Time:02-18

I've got an JSON Array listed below:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": [
    {
      "_id": "6125496b64ec43ef984a48ad",
      "imdb_id": "tt10872600",
      "name": "Spider-Man: No Way Home",
      "type": "movie",
      "year": "2021"
    },
    {
      "_id": "61f3e33b64ec43ef98553e07",
      "imdb_id": "tt13634480",
      "name": "The Ice Age Adventures of Buck Wild",
      "type": "movie",
      "year": "2022"
    },
    {
      "_id": "5c4f384dd582b25756275494",
      "imdb_id": "tt9032400",
      "name": "Eternals",
      "type": "movie",
      "year": "2021"
    }
  ]
}

I'm wanting to make a function to search through this array by imdb_id or name (not both). How would I go about doing this?

My poor attempt:

const json = require('./test.json');
function Search(file){
  for (let i = 0; i < file.length; i  ) {
    console.log(file[i].results[i].imdb_id);
  }
}
Search(json);

CodePudding user response:

At simplest, you could leverage the inbuilt filtering function, something like this

const idOrNameEquals = searchStr => item => item.imdb_id === searchStr || item.name === searchStr

const json = require('./test.json')
const foundItems = json.result.filter(idOrNameEquals('Eternals'))

CodePudding user response:

try using filter

function SearchJson(json, imdb_id, name){
  return json.result.filter( function(item) {
    return   imdb_id==null?  item.name == name : item.imdb_id==imdb_id
  });
};

test

 var result= SearchJson(json,null, "Eternals");

result

[
  {
    "_id": "5c4f384dd582b25756275494",
    "imdb_id": "tt9032400",
    "name": "Eternals",
    "type": "movie",
    "year": "2021"
  }
]
  • Related