Home > Software design >  How to get another field of same object in JSON with vanilla JS?
How to get another field of same object in JSON with vanilla JS?

Time:05-24

I have a JSON like this:

[
 {
  "title": "film1",
  "actor": ["jack", "fred"]
 },
 {
   "title": "film2",
   "actor": ["jack", "tom"]
 },
 {
  "title": "film3",
  "actor": ["albert", "luke"]
 }
]

There is an input element where the user can search inside this JSON. When the user type a string, the app should return a list of the corresponding "title" fields.

Example: The user types "jack". The app should return:

- film1
- film2

Because the string "jack" is only in the "actor" array of film1 and film2.

How do I code this? I think I should use Object.values and Array.prototype.reduce() but I'm not sure how.

CodePudding user response:

Using JavaScript array methods

Use Array.filter and Array.map and Array.some for a one line solution. To make the search case-insensitive we also need to convert both the keyword and the actor name to uppercase before doing the compare.

films.filter(p => p.actor.some(name => name.toUpperCase() === keyword)).map(p => p.title);

Run the snippet to understand how it works

let films = [
 {
  "title": "film1",
  "actor": ["jack", "fred"]
 },
 {
   "title": "film2",
   "actor": ["jack", "tom"]
 },
 {
  "title": "film3",
  "actor": ["albert", "luke"]
 }
];


search.onchange = function(e) {

  let keyword = (search.value || "").trim().toUpperCase();
  
  let result =  films.filter(p => p.actor.some(name => name.toUpperCase() === keyword)).map(p => p.title);
  
  if (!result.length) result.push("No matches");
  
  output.innerHTML = "<li>"   result.join("</li><li>")   "</li>";
  
}

search.onchange();
<p>Enter a keyword and press enter:</p>
<input id="search" type="text" value="Jack">

<ul id="output"></ul>

CodePudding user response:

try this

var actor = "jack";
var films = [];
actors.forEach((item) => {
  if (item.actor.includes(actor)) films.push(item.title);
});
console.log(films);
  • Related