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

139
Visualizações
Get item from js object with partially known key

Let's say you dont know the numbers before the letter here.

var obj = {'1234 x': 1, '32145 y': 2}

How would you retrieve the value 1 from this object.

The normal way of doing this would be:

obj['1234 x'] // 1

But what if you only knew part of the key: 'x' (the part that comes after the first space)

var key = '1234 x',
    known_key = key.split(' ')[0] // 'x'

How would you be able to retrieve this value?

obj['% ' + known_key] // 1
// % represents all possible strings
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use a filter.

Retrieve the key and value

function findObject(obj, known_key) {
  return Object.fromEntries(
    Object.entries(obj)
    .filter(e =>
      e[0].substr(e[0].indexOf(' ') + 1) == known_key
    )
  )
}

var object = {
    '1234 x': 1,
    '32145 y': 2,
    '987 y': 3
  },
  key = 'y'

console.log(  
  findObject(object, key) // {'32145 y': 2, '987 y': 3}
)

Retrieve the value

function findValue(obj, known_key) {
  return Object.entries(obj)
  .filter(e =>
    e[0].substr(e[0].indexOf(' ') + 1) == known_key
  )
  .map(e => e[1])
}

var object = {
    '1234 x': 1,
    '32145 y': 2,
    '987 y': 3
  },
  key = 'y'

console.log(
  findValue(object, key) // [2, 3]
)

about 4 years ago · Juan Pablo Isaza Relatório

0

Filter using endsWith - you can substitute with includes to find the string anywhere

const findPartial = (obj,str) => Object.fromEntries(Object.entries(obj)
  .filter(([key, val]) => key.endsWith(str)));

const obj = {
  '1234 x': 1,
  '32145 y': 2
}
console.log(
  findPartial(obj, ' y')
)

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