我有一个包含一个或多个对象的数组,我想过滤掉所有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);
但是我又得到了相同的对象属性。我想念什么?
听起来好像您想使用仅具有非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);