当前位置:  开发笔记 > 编程语言 > 正文

Javascript过滤器空对象属性

如何解决《Javascript过滤器空对象属性》经验,为你挑选了1个好方法。

我有一个包含一个或多个对象的数组,我想过滤掉所有null属性:

asset = [{"ObjId":177791,"ObjCreditlineM":"DEU","ObjReprorechtM":null,"ObjKommentarM":null,"ObjZustandM":null,"ObjReserve01M":null,"ObjReserve02M":null,"ObjFeld01M":null,"ObjFeld02M":null,"ObjFeld03M":null,"ObjFeld04M":"Foto","ObjFeld05M":null,"ObjFeld06M":null,"ObjFeld07M":null,"ObjFeld01S":null,"ObjFeld02S":null,"ObjFeld03S":null,"ObjFeld04S":null,"ObjFeld05S":null,"ObjFeld06S":null,"ObjFeld07S":null,"ObjFeld01F":0,"ObjFeld02F":0,"ObjFeld01D":null,"ObjFeld02D":null,"ObjInv01S":null,"ObjInv02S":null,"ObjInv03S":null,"ObjInv04S":null,"ObjInv05S":null,"ObjInv06S":null,"ObjDinId":0,"ObjReferenz01Id":null,"ObjReferenz02Id":null,"ObjTransferId":null,"ObjGesperrtS":null,"ObjIconTextM":null}]


// My attempt:

var filledProps = asset.map(el => { 
  if (Object.keys(el)) { // check if object property value is not null
    return el;
  };
});

console.log(filledProps);

但是我又得到了相同的对象属性。我想念什么?



1> T.J. Crowder..:

听起来好像您想使用仅具有非null原始属性的新对象创建新数组。是的,这map是您要开始的地方,但Object.keys(el)始终是真实的,因为它返回属性名称数组。您虽然接近:

var asset = [{"ObjId":177791,"ObjCreditlineM":"DEU","ObjReprorechtM":null,"ObjKommentarM":null,"ObjZustandM":null,"ObjReserve01M":null,"ObjReserve02M":null,"ObjFeld01M":null,"ObjFeld02M":null,"ObjFeld03M":null,"ObjFeld04M":"Foto","ObjFeld05M":null,"ObjFeld06M":null,"ObjFeld07M":null,"ObjFeld01S":null,"ObjFeld02S":null,"ObjFeld03S":null,"ObjFeld04S":null,"ObjFeld05S":null,"ObjFeld06S":null,"ObjFeld07S":null,"ObjFeld01F":0,"ObjFeld02F":0,"ObjFeld01D":null,"ObjFeld02D":null,"ObjInv01S":null,"ObjInv02S":null,"ObjInv03S":null,"ObjInv04S":null,"ObjInv05S":null,"ObjInv06S":null,"ObjDinId":0,"ObjReferenz01Id":null,"ObjReferenz02Id":null,"ObjTransferId":null,"ObjGesperrtS":null,"ObjIconTextM":null}]

// Use `map` to get a new array with new objects
var filledProps = asset.map(el => {
  // Loop the property names of `el`, creating a new object
  // with the ones whose values aren't `null`.
  // `reduce` is commonly used for doing this:
  return Object.keys(el).reduce((newObj, key) => {
    const value = el[key];
    if (value !== null) {
      newObj[key] = value;
    }
    return newObj;
  }, {});
});
console.log(filledProps);
推荐阅读
雨天是最美
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有