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

134
Visualizações
Filtrar objeto por clave y valor

¿Hay alguna forma de filtrar un objeto comprobando condicionalmente tanto la clave como el valor? Lo que estoy tratando de hacer es verificar si la clave es igual a una cadena y verificar si el valor está vacío o no.

Estoy tratando de detectar si Teaching Hospital tiene o no un valor vacío, pero Teaching Hospital Tax ID no lo tiene y viceversa. Si el nombre del hospital docente tiene un valor, pero el ID fiscal del hospital docente no lo tiene, el resultado devuelto debe ser: {ID fiscal del hospital docente: ""}.

Objeto

 { 'Manufacturer Name': 'Ascendis', 'HCP First Name': 'John', 'HCP Middle Name': '', 'HCP Last Name': '', 'HCP NPI': 2442, 'HCP Credentials': '', 'HCP State License Number': '', 'HCP State of Licensure': '', 'HCP Specialty': '', 'Teaching Hospital Name': 'Trinity', 'Teaching Hospital Tax ID': '', 'Address 1': '', 'Address 2': '', 'Postal Code': '', 'Spend Date': '', 'Spend Currency': '', 'Spend Amount': '', 'Form of Payment': '', 'Nature of Payment': '', 'Home System Identifier': '', 'Product Name': '', 'Travel City': '', 'Travel State': '', 'Travel Country': '' }

Código

 Object.entries(item) .filter(([key, value]) => (key === "Teaching Hospital Name" && value != "") && (key === "Teaching Hospital Tax ID" && value === ""))
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Uso || en lugar de && :

 const obj = { 'Manufacturer Name': 'Ascendis', 'HCP First Name': 'John', 'HCP Middle Name': '', 'HCP Last Name': '', 'HCP NPI': 2442, 'HCP Credentials': '', 'HCP State License Number': '', 'HCP State of Licensure': '', 'HCP Specialty': '', 'Teaching Hospital Name': 'Trinity', 'Teaching Hospital Tax ID': '', 'Address 1': '', 'Address 2': '', 'Postal Code': '', 'Spend Date': '', 'Spend Currency': '', 'Spend Amount': '', 'Form of Payment': '', 'Nature of Payment': '', 'Home System Identifier': '', 'Product Name': '', 'Travel City': '', 'Travel State': '', 'Travel Country': '' } Object.entries(obj).forEach(([key, value]) => { if ((key === "Teaching Hospital Name" && value != "") || (key === "Teaching Hospital Tax ID" && value === "")) { delete obj[key] } }) console.log(obj)

about 4 years ago · Juan Pablo Isaza Relatório

0

Puede usar Array.prototype.reduce para crear un nuevo objeto con las propiedades de selección eliminadas:

 Object.entries(obj).reduce((acc, [key, value]) => { if ( (key === "Teaching Hospital Name" && value !== "") || (key === "Teaching Hospital Tax ID" && value === "") ) { // do not add key/value to resulting object return { ...acc }; } return { ...acc, [key]: value }; }, {});

Esto evita mutar el objeto original.

about 4 years ago · Juan Pablo Isaza Relatório

0

Analicemos lo que tenemos y lo que queremos.

  • Tenemos un modelo obj .
  • Queremos elegir claves específicas y ejecutar comprobaciones específicas contra claves/valores seleccionados
  • La verificación devuelve el objeto con esas claves cuyos valores son cadenas vacías
  • Además, la verificación ignorará los resultados si todos los valores están vacíos

Podríamos escribir arriba como

 1. if(allValues has an empty string) return false // ignore results 2. if(allValues has NOT an empty string) return false // ignore 3. results 3. return object with those keys where value is empty string

que en JS se vería como

 // your model const obj = {} // your group of keys you want to pick from object const group = []; // picked [[key,value]] defined by your group const entries = Object.entries(obj).filter(([key]) => group.includes(key)); // filter out those which are empty const emptyEntries = entries.filter(([key, value]) => value === ""); // 1. step - to check if all values are empty we can check lengths if(entries.length === emptyEntries.length) return false; // 2. step - just check if filtered length is 0 if(emptyEntries.length === 0) return false // 3. step - convert your emptyEntries to object return Object.fromEntries(emptyEntries);

Veamos si el siguiente código funciona para usted

 const obj = { 'Manufacturer Name': 'Ascendis', 'HCP First Name': 'John', 'HCP Middle Name': '', 'HCP Last Name': '', 'HCP NPI': 2442, 'HCP Credentials': '', 'HCP State License Number': '', 'HCP State of Licensure': '', 'HCP Specialty': '', 'Teaching Hospital Name': 'Trinity', 'Teaching Hospital Tax ID': '', 'Address 1': '', 'Address 2': '', 'Postal Code': '', 'Spend Date': '', 'Spend Currency': '', 'Spend Amount': '', 'Form of Payment': '', 'Nature of Payment': '', 'Home System Identifier': '', 'Product Name': '', 'Travel City': '', 'Travel State': 'nonempty', 'Travel Country': '' } function check(obj, groupArr) { const group = new Set(groupArr); const vals = Object.entries(obj).filter(([key, value]) => group.has(key) && value === ""); if(vals.length === group.size || vals.length === 0) return false; return Object.fromEntries(vals); } console.log(check(obj, ["Travel City", "Travel State", "Travel Country"])); /* results { "Travel City": "", "Travel Country": "" } */

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