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

181
Visualizações
How to get an object from one key,value in array

I have the following code which returns whether the key and value are found in an array object.

function iterate(array, prop, val) {
    Object.keys(array).forEach((key) => {
        if (key === prop && val === array[key]) {
            console.log(`key: ${key}, value: ${array[key]}`);
        }

        if (typeof array[key] === 'object') {
            iterate(array[key], prop, val);
        }
    });
}

That's ok but now I would like to access the full content of that specific object where those properties and values were found. This is my JSON:

[
   {
      "page":"main",
      "content":[
         {
            "type":"item",
            "item":[
               {
                  "name":"HAMMER",
                  "price":"1000"
               },
               {
                  "name":"SWORD",
                  "price":"2000"
               }
            ]
         }
      ]
   }
]

This is what I look for/get with my function:

"name":"HAMMER"

And this is what I need:

{
   "name":"HAMMER",
   "price":"1000"
},

Is there any way to achieve that or am I addressing this problem from the wrong perspective?

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

0

You could use a basic loop, to find an item from deep nested object...

let data = [{ "page": "main", "content": [{ "type": "item", "item": [{ "name": "HAMMER", "price": "1000" }, { "name": "SWORD", "price": "2000" }] }] }]
let [prop, value] = ["name", "HAMMER"]

loop: for (let page of data) {
    for (let type of page.content) {
        let found = type.item.find(v => v[prop] === value);
        if (found) {
            console.log(found)
            break loop;
        }
    }
}

would you like to lookup recursively? Then you can use a generator...

let data = [{ "page": "main", "content": [{ "type": "item", "item": [{ "name": "HAMMER", "price": "1000" }, { "name": "SWORD", "price": "2000" }] }] }]

function* iterate(arrayLike, prop, value) {
    for (let page of arrayLike) {
        if (page[prop] == value)
            yield page;

        for (let v of Object.values(page)) {
            if (Array.isArray(v))
                yield* iterate(v, prop, value)
        }
    }
}

for (let item of iterate(data, "name", "HAMMER")) {
    console.log(item)
}

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