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: '' }' ] }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.
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))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" }]))