Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How to get another field of same object in JSON with vanilla JS?

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

try this

var actor = "jack";
var films = [];
actors.forEach((item) => {
  if (item.actor.includes(actor)) films.push(item.title);
});
console.log(films);
about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda