无法从数组内的对象中删除空元素

时间:2019-07-25 13:22:13

标签: javascript

我有一个具有以下结构的对象数组:

{"fecha":"24-07-2019",
  "local_id":"5",
  "local_nombre":"AHUMADA",
  "comuna_nombre":"LA CALERA",
  "fk_localidad":"12",
  "localidad_nombre":"LA CALERA",
  "local_direccion":"J J PEREZ 199",
  "funcionamiento_hora_apertura":"09:00 hrs.",
  "funcionamiento_hora_cierre":"08:59 hrs.",
  "local_telefono":"+563326316573",
  "local_lat":"-32.7882065329844",
  "local_lng":"-71.189446195146",
  "funcionamiento_dia":"Miercoles",
  "fk_region":"6"
}

此对象有时1或2个元素为空"",并且我需要删除它们

问题是我尝试了很多操作来删除它们,但是我总是得到null对象的数组。

我尝试过的事情

  const deleteEmpty = obj => {
    for (let prop in obj) {
      if (obj[prop] === null || obj[prop] === undefined) {
        console.log(obj[prop])
        delete obj[prop]
      }
    }
  }

// Supose my array of objects is in a const named 'objArr'
   const newObjArr = objArr.map(obj => {
     deleteEmpty(obj)
   })

也尝试过

   const newArr = objArr.map(obj => {
     Object.keys(obj).forEach(
       key => obj[key] === null && delete obj[key]
     )
   }

正如我所说,我得到的nulls数组的长度与删除过程中放入的第一个数组的长度相同。不知道我在做什么错。

致谢。

4 个答案:

答案 0 :(得分:5)

您必须在函数末尾返回对象

  const deleteEmpty = obj => {
    for (let prop in obj) {
      if (obj[prop] === null || obj[prop] === undefined) {
        console.log(obj[prop])
        delete obj[prop]
      }
    }
    return obj
  }

答案 1 :(得分:3)

deleteEmpty不会将obj返回

const deleteEmpty = obj => {
  for (let prop in obj) {
    if (obj[prop] === null || obj[prop] === undefined) {
      console.log(obj[prop])
      delete obj[prop]
    }
  }

  return obj
}

答案 2 :(得分:1)

如果用空表示空字符串“”,则应在检查中包括空字符串不等于null或未定义

答案 3 :(得分:1)

您可以使用Array.prototype.reduce来制作元素的副本,只需忽略任何空白值即可:

const elements = [{
  "fecha": "24-07-2019",
  "local_id": "5",
  "local_nombre": "AHUMADA",
  "comuna_nombre": "LA CALERA",
  "fk_localidad": "12",
  "localidad_nombre": "LA CALERA",
  "local_direccion": "J J PEREZ 199",
  "funcionamiento_hora_apertura": "09:00 hrs.",
  "funcionamiento_hora_cierre": "08:59 hrs.",
  "local_telefono": "",
  "local_lat": "",     //Blank
  "local_lng": "",     //Blank
  "funcionamiento_dia": "Miercoles",
  "fk_region": "6"
}, {
  "fecha": "24-07-2019",
  "local_id": "5",
  "local_nombre": "",   //Blank
  "comuna_nombre": "LA CALERA",
  "fk_localidad": "12",
  "localidad_nombre": "LA CALERA",
  "local_direccion": "J J PEREZ 199",
  "funcionamiento_hora_apertura": "09:00 hrs.",
  "funcionamiento_hora_cierre": "08:59 hrs.",
  "local_telefono": "", //Blank
  "local_lat": "-37.6",
  "local_lng": "24.5",
  "funcionamiento_dia": "Miercoles",
  "fk_region": "6"
}];

const copyWithoutBlanks = el => {
  return Object.entries(el).reduce((accum, entry) => {
    const [key, val] = entry;
    if (val.trim().length) {
      accum[key] = val;
    }
    return accum;
  }, {});
};

const noBlanks = arr => arr.map(copyWithoutBlanks);

console.log(noBlanks(elements))