0

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);

2 Answers 2

1

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'))
Sign up to request clarification or add additional context in comments.

Comments

1

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"
  }
]

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.