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

115
Visualizações
¿Eliminar el campo de cadena vacío de un objeto que contiene un objeto anidado y una matriz?

He hecho otra pregunta, pero alguien cierra esa pregunta. Realmente necesito esta respuesta. Por eso hago otra pregunta.

Tengo un objeto como el siguiente. Tengo que eliminar esa cadena vacía archivada del objeto anidado y también de la matriz anidada. Como puedo quitar eso.

 const obj = { name: 'Red Boy', price: '350', originalPrice: '', // Empty string field stock: 20, category: { name: '', // Empty String field subCategory: { name: ''} // Empty String filed }, weight: '90kg', dimensions: { width: '50cm', height: '', // Empty string filed length: '70cm' }, suitable: [ { name: 'Yoga' }, { name: '' }, // Empty String filed { name: 'Winter' } ], additionalInfo: [ { field: 'closure', value: 'Button' }, { field: 'collar', value: ''} // Empty String Field ] }

En este tipo de objeto híbrido, puede ver algunos subobjetos y también algunos subconjuntos. También puede ver algunos campos que no contienen ningún valor (comento ese campo).

En realidad, necesito eliminar ese archivo. ¿Cómo puedo eliminar ese campo de cadena vacío del tipo de objeto híbrido anterior?

Gracias..

Mi resultado esperado-

 { name: 'Red Boy', price: '350', // Removed stock: 20, category: { name: '', // Empty String field // Removed }, weight: '90kg', dimensions: { width: '50cm', // Removed length: '70cm' }, suitable: [ { name: 'Yoga' }, //Removed { name: 'Winter' } ], additionalInfo: [ { field: 'closure', value: 'Button' }, { field: 'collar', //Removed } // Here If this two filed is empty then should remove the whole object { field: '', value: '' } // Then should remove whole '{ field: '', value: '' }' ] }
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Para lograr esto, necesitamos implementar una función recursiva para eliminar todas las cadenas vacías en todas las matrices y objetos anidados.

 function rec(obj){ for(let key of Object.keys(obj)){ if (obj[key] === ''){ delete obj[key]; } else if (typeof obj[key] === 'object'){ obj[key] = rec(obj[key]); if (Object.keys(obj[key]).length === 0 ) delete obj[key]; } } return Array.isArray(obj) ? obj.filter(val => val) : obj; }

Además, tenga en cuenta que no es puramente híbrido. Porque Array es un tipo especial de Objeto.

about 4 years ago · Juan Pablo Isaza Relatório

0

 const obj = { name: 'Red Boy', price: '350', originalPrice: '', // Empty string field stock: 20, category: { name: '', // Empty String field subCategory: { name: ''} // Empty String filed }, weight: '90kg', dimensions: { width: '50cm', height: '', // Empty string filed length: '70cm' }, suitable: [ { name: 'Yoga' }, { name: '' }, // Empty String filed { name: 'Winter' } ], additionalInfo: [ { field: 'closure', value: 'Button' }, { field: 'collar', value: ''} // Empty String Field ] } function removeEmptyString(object) { Object .entries(object) .forEach(([key, value]) => { if (value && typeof value === 'object') removeEmptyString(value); if (value && typeof value === 'object' && !Object.keys(value).length || value === null || value === undefined || value.length === 0 ) { if (Array.isArray(object)) object.splice(key, 1); else delete object[key]; } }); return object; } console.log(removeEmptyString(obj))

about 4 years ago · Juan Pablo Isaza Relatório

0

He usado recursion para filtrar la empty string empty object vacío o la empty array presente en el interior de la estructura anidada.

Esta función también elimina dichos objetos y sus objetos anidados sin propiedades.

Note: It will also work if the provided initial value is any other thing then object like array or string

 var obj={name:"Red Boy",price:"350",originalPrice:"",stock:20,category:{name:"",subCategory:{name:""}},weight:"90kg",dimensions:{width:"50cm",height:"",length:"70cm"},suitable:[{name:"Yoga"},{name:""},{name:"Winter"}],additionalInfo:[{field:"closure",value:"Button"},{field:"collar",value:""}]}; function filt(a) { if (typeof a === 'string') return a !== ''; //if it is a string, then it must not be empty else if (Array.isArray(a)) return a.length !== 0 //if it an arra, then it must have some item else if (a instanceof Object) return Object.keys(a).length !== 0; //if it is an object, then it must have some property return a !== null && a !== undefined //else it must not be null or undefined } function rec(obj) { if (Array.isArray(obj)) { //if an value is an array return obj.map((a) => rec(a)).filter((a) => filt(a)) //recurse the child first of each value in the array //then filter out the value which are either null, empty, undefined or have length 0 } else if (obj instanceof Object) { //if value is an object var d = Object.entries(obj).map((a) => ([a[0], rec(a[1])])).filter((a) => filt(a[1])); //map through the object.entries and reassign the values to the keys by recurssing over the value to filter out the nested inside irrelevant value return Object.fromEntries(d) //convert the map into object and return } else if (typeof obj === 'string') return obj !== '' ? obj : null //f it is a string, it must not be empty else return null return obj !== null && obj !== undefined ? obj : null //else it must not be null or undefined } console.log("For object",rec(obj)) console.log("For Array",rec([{ name: "Yoga" }, { name: "" }, { name: "Winter" }]))

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