0

Tengo un array extraido de un pdf y deseo eliminar todos aquellos elementos que tengan la cadena str vacia,

    {
    "meta": {
    "info": {
        "PDFFormatVersion": "1.4",
            "Language": null,
            "EncryptFilterName": null,
            "IsLinearized": false,
            "IsAcroFormPresent": false,
            "IsXFAPresent": false,
            "IsCollectionPresent": false,
            "IsSignaturesPresent": false,
            "Creator": "JasperReports (reporteSemanasCotizadas)",
            "Producer": "iText 2.1.7 by 1T3XT",
            "ModDate": "D:20220713094658-05'00'",
            "CreationDate": "D:20220713094658-05'00'"
    },
    "metadata": null
},
    "pages": [
    {
        "pageInfo": {
            "num": 1,
            "scale": 1,
            "rotation": 0,
            "offsetX": 0,
            "offsetY": 0,
            "width": 612,
            "height": 792
        },
        "links": [],
        "content": [
            {
                "x": 225.13,
                "y": 108.78999999999996,
                "str": "Instituto Mexicano del Seguro Social",
                "dir": "ltr",
                "width": 161.7399999999999,
                "height": 10,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 438.82,
                "y": 210.27999999999997,
                "str": "DD",
                "dir": "ltr",
                "width": 8.664,
                "height": 6,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 460.82800000000003,
                "y": 210.27999999999997,
                "str": "MM",
                "dir": "ltr",
                "width": 9.996,
                "height": 6,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 484.16800000000006,
                "y": 210.27999999999997,
                "str": "YYYY",
                "dir": "ltr",
                "width": 16.008,
                "height": 6,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 247.53,
                "y": 282.04,
                "str": "Tu detalle de semanas cotizadas",
                "dir": "ltr",
                "width": 116.94399999999999,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 201.57,
                "y": 141.78999999999996,
                "str": "Constancia de Semanas Cotizadas en el IMSS",
                "dir": "ltr",
                "width": 207.8699999999999,
                "height": 10,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 462.83,
                "y": 245.03999999999996,
                "str": "363",
                "dir": "ltr",
                "width": 13.344000000000001,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 47,
                "y": 226.03999999999996,
                "str": "NSS:",
                "dir": "ltr",
                "width": 18.672,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 47,
                "y": 205.03999999999996,
                "str": "HERNANDEZ HIGUERA CARLOS ABDIEL",
                "dir": "ltr",
                "width": 154.24800000000002,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 70,
                "y": 226.03999999999996,
                "str": "21139682674",
                "dir": "ltr",
                "width": 48.928000000000004,
                "height": 8,
                "fontName": "Helvetica"
            }
        ]
    },
    {
        "pageInfo": {
            "num": 2,
            "scale": 1,
            "rotation": 0,
            "offsetX": 0,
            "offsetY": 0,
            "width": 612,
            "height": 792
        },
        "links": [],
        "content": [
            {
                "x": 225.13,
                "y": 108.78999999999996,
                "str": "Instituto Mexicano del Seguro Social",
                "dir": "ltr",
                "width": 161.7399999999999,
                "height": 10,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 312,
                "y": 216.95000000000005,
                "str": "17/09/2021",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 147,
                "y": 196.95000000000005,
                "str": "BAJA CALIFORNIA",
                "dir": "ltr",
                "width": 70.23999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 388,
                "y": 216.95000000000005,
                "str": "Salario Base de Cotización */",
                "dir": "ltr",
                "width": 103.59999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 216.95000000000005,
                "str": "Fecha de alta",
                "dir": "ltr",
                "width": 48.472000000000016,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 232,
                "y": 216.95000000000005,
                "str": "Fecha de baja",
                "dir": "ltr",
                "width": 50.695999999999984,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 147,
                "y": 216.95000000000005,
                "str": "20/01/2020",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 196.95000000000005,
                "str": "Entidad federativa",
                "dir": "ltr",
                "width": 64.48,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 518.86,
                "y": 216.95000000000005,
                "str": "$ 620.67",
                "dir": "ltr",
                "width": 31.13600000000005,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 156.95000000000005,
                "str": "Nombre del patrón",
                "dir": "ltr",
                "width": 66.24800000000002,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 147,
                "y": 156.95000000000005,
                "str": "TCL MOKA MANUFACTURING",
                "dir": "ltr",
                "width": 113.33599999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 176.95000000000005,
                "str": "Registro Patronal",
                "dir": "ltr",
                "width": 61.80000000000001,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 147,
                "y": 176.95000000000005,
                "str": "A086348210",
                "dir": "ltr",
                "width": 45.368,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 322.26,
                "y": 252.03999999999996,
                "str": "Fecha de movimiento",
                "dir": "ltr",
                "width": 76.47199999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 129.6,
                "y": 252.03999999999996,
                "str": "Tipo de movimiento",
                "dir": "ltr",
                "width": 69.79999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 479.32,
                "y": 252.03999999999996,
                "str": "Salario Base",
                "dir": "ltr",
                "width": 45.352,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 340.48,
                "y": 272.03999999999996,
                "str": "17/09/2021",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 154.5,
                "y": 272.03999999999996,
                "str": "BAJA",
                "dir": "ltr",
                "width": 20.008000000000003,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 486.43,
                "y": 272.03999999999996,
                "str": "$ 620.67",
                "dir": "ltr",
                "width": 31.135999999999992,
                "height": 8,
                "fontName": "Helvetica"
            },
        ]
    },
    {
        "pageInfo": {
            "num": 3,
            "scale": 1,
            "rotation": 0,
            "offsetX": 0,
            "offsetY": 0,
            "width": 612,
            "height": 792
        },
        "links": [],
        "content": [
            {
                "x": 225.13,
                "y": 108.78999999999996,
                "str": "Instituto Mexicano del Seguro Social",
                "dir": "ltr",
                "width": 161.7399999999999,
                "height": 10,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 322.26,
                "y": 141.03999999999996,
                "str": "Fecha de movimiento",
                "dir": "ltr",
                "width": 76.47199999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 129.6,
                "y": 141.03999999999996,
                "str": "Tipo de movimiento",
                "dir": "ltr",
                "width": 69.79999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 479.32,
                "y": 141.03999999999996,
                "str": "Salario Base",
                "dir": "ltr",
                "width": 45.352,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 340.48,
                "y": 161.03999999999996,
                "str": "01/07/2019",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 109.82,
                "y": 161.03999999999996,
                "str": "MODIFICACION DE SALARIO",
                "dir": "ltr",
                "width": 109.35199999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 486.43,
                "y": 161.03999999999996,
                "str": "$ 325.18",
                "dir": "ltr",
                "width": 31.135999999999992,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 340.48,
                "y": 181.03999999999996,
                "str": "24/06/2019",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 140.5,
                "y": 181.03999999999996,
                "str": "REINGRESO",
                "dir": "ltr",
                "width": 48.007999999999996,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 486.43,
                "y": 181.03999999999996,
                "str": "$ 324.74",
                "dir": "ltr",
                "width": 31.135999999999992,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 42,
                "y": 201.03999999999996,
                "str": "/* Valor del último salario base de cotización diario en pesos.",
                "dir": "ltr",
                "width": 215.64800000000008,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 312,
                "y": 301.95,
                "str": "26/06/2019",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 147,
                "y": 281.95,
                "str": "BAJA CALIFORNIA",
                "dir": "ltr",
                "width": 70.23999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 388,
                "y": 301.95,
                "str": "Salario Base de Cotización */",
                "dir": "ltr",
                "width": 103.59999999999998,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 301.95,
                "str": "Fecha de alta",
                "dir": "ltr",
                "width": 48.472000000000016,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 232,
                "y": 301.95,
                "str": "Fecha de baja",
                "dir": "ltr",
                "width": 50.695999999999984,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 147,
                "y": 301.95,
                "str": "23/05/2018",
                "dir": "ltr",
                "width": 40.032000000000004,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 281.95,
                "str": "Entidad federativa",
                "dir": "ltr",
                "width": 64.48,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 518.86,
                "y": 301.95,
                "str": "$ 324.74",
                "dir": "ltr",
                "width": 31.13600000000005,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 241.95000000000005,
                "str": "Nombre del patrón",
                "dir": "ltr",
                "width": 66.24800000000002,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 147,
                "y": 241.95000000000005,
                "str": "NOMINA INTEGRAL DE SOLUCIONES PRODUCTIVAS",
                "dir": "ltr",
                "width": 202.25600000000006,
                "height": 8,
                "fontName": "Helvetica"
            },
            {
                "x": 44,
                "y": 261.95000000000005,
                "str": "Registro Patronal",
                "dir": "ltr",
                "width": 61.80000000000001,
                "height": 8,
                "fontName": "Helvetica"
            },
            {},
            {
                "x": 147,
                "y": 261.95000000000005,
                "str": "Z312983510",
                "dir": "ltr",
                "width": 44.92,
                "height": 8,
                "fontName": "Helvetica"
            }
        ]
    },
],
    "filename": "./Employees/123.pdf"
}

estoy usando esta funcion y elimina las cadenas pero queda el {} vacio

function eliminarVacios(jsonx){
    for (var str in jsonx) {
        if(typeof jsonx[str] == 'string'){
            if(jsonx[str] == ' '||jsonx[str] == ''){
                delete jsonx.str
                delete jsonx.x
                delete jsonx.y
                delete jsonx.dir
                delete jsonx.width
                delete jsonx.height
                delete jsonx.fontName
            }
        } else if (typeof jsonx[str] == 'object') {
            eliminarVacios(jsonx[str])
        }
    }
    return jsonx
}

esto me devuelve el array asi:

"content": [
                {
                    "x": 225.13,
                    "y": 108.78999999999996,
                    "str": "Instituto Mexicano del Seguro Social",
                    "dir": "ltr",
                    "width": 161.7399999999999,
                    "height": 10,
                    "fontName": "Helvetica"
                },
                {}, // deseo eliminar esto
                {
                    "x": 438.82,
                    "y": 210.27999999999997,
                    "str": "DD",
                    "dir": "ltr",
                    "width": 8.664,
                    "height": 6,
                    "fontName": "Helvetica"
                },
            ]

como podria eliminar todo completo?

2
  • Te convendría usar filter, haciendo algo así jsonx.content.filter(e=>e.str.replace(/ +/g,"")); pero parece que la estructura puede ser mas compleja que el ejemplo que pones, o la estructura pude variar, no?.
    – Emeeus
    Commented el 14 jul. 2022 a las 0:17
  • Si, toda la estructura es igual, aqui seria solo eliminar el elemento completo si la cadena str = " ", pero no logro hacerlo! Commented el 14 jul. 2022 a las 1:07

3 respuestas 3

2

Como sugerí en los comentarios, se podría usar .filter:

const jsonx ={"meta":{"info":{"PDFFormatVersion":"1.4"},"metadata":null},"pages":[{"pageInfo":{"num":1},"links":[],"content":[{"str":"21139682674"},{"str":""},{"str":" "},{"str":"  "}]},{"pageInfo":{"num":2},"links":[],"content":[{"str":"$ 620.67"},{"str":""},{"str":" "},{"str":"  "}]},{"pageInfo":{"num":3},"links":[],"content":[{"str":"Z312983510"},{"str":""},{"str":" "},{"str":"  "}]}],"filename":"./Employees/123.pdf"};

jsonx.pages.forEach((p,i,o)=>o[i].content = p.content.filter(e=>e.str.replace(/ +/g,"")));

console.log(jsonx);

El objeto de ejemplo lo reduje a la mínima expresión para hacerlo mas ameno.

1

Por la estructura de tu objeto, básicamente necesitas recorrer los arreglos de pages y verificar el content de cada página. Si el objeto de contenido está vacío o tiene el string vacío, elimínalo con splice. Quedaría tu función algo así:

function eliminarVacios(jsonx) {
    let pages = jsonx.pages || [];
    for (let i = 0; i < pages.length; i++) {
        let content = pages[i].content;
        for (let j = 0; j < content.length; j++) {
            if (content[j].str == "" || content[j].str == null) {
                content.splice(j, 1);
                j--;
            }
        }
    }

    return jsonx;
}
3
  • Hola Jaime, gracias por responder, tu respuesta es correcta pero el problema es que el json es mas amplio, tiene mas niveles, aqui no me deja escribir codigo, asi que respondere en otra respuesta a ver si puedes ayudarme Commented el 14 jul. 2022 a las 5:16
  • @AbdielHernandez conviene que pongas en tu pregunta la estructura completa. Sin ver los datos de entrada es difícil realizar la función que necesitas.
    – Jaime
    Commented el 14 jul. 2022 a las 5:23
  • Wow! quedo excelente, es justo lo que necesitaba, eres un master! por favor si es posible hacerme llegar tu email, me gustaria ponerme en contacto contigo, mi correo es [email protected] Commented el 14 jul. 2022 a las 6:03
0

Deseas eliminar todos los objetos que contengan alguna key con valor ""

const res = jsonx.filter((item) => {

const containEmptyStr = (obj) => {
    let res = false;
    Object.keys(obj).forEach((key) => {
      if (obj[key] === "") res = true;
    });
    return res;
  };
  return !containEmptyStr(item)
});

console.log(res);

Esto te devolverá otro array con todos aquellos objetos que NO contengan alguna key con valor ""

let jsonx = [
    {
        "x": 225.13,
        "y": 108.78999999999996,
        "str": "Instituto Mexicano del Seguro Social",
        "dir": "ltr",
        "width": 161.7399999999999,
        "height": 10,
        "fontName": "Helvetica"
    },
   
    {
        "x": 438.82,
        "y": 210.27999999999997,
        "str": "DD",
        "dir": "ltr",
        "width": 8.664,
        "height": 6,
        "fontName": "Helvetica"
    },
]

Editado Usando la misma logica, haciendo mas profunda la busqueda y partiendo de que siempre se recibe y se espera el mismo formato

const filterObjectWhithEmptyStrs = (array) => {
  const res = array.filter((item) => {
    const containEmptyStr = (obj) => {
      let res = false;
      Object.keys(obj).forEach((key) => {
        if (obj[key] === "") res = true;
      });
      return res;
    };
    return !containEmptyStr(item);
  });
  return res;
};

const scanPdf = (pdf) => {
  let pages;
  Object.keys(pdf).forEach((key) => {
    if (key === "pages") {
      pages = pdf[key].map((page) => {
        return { ...page, content: filterObjectWhithEmptyStrs(page.content) };
      });
    }
  });

  return { ...pdf, pages };
};

Puedes editarlo aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.