如何使用扩展运算符(spread operator)过滤对象中的null值
问题与解决方案
需求与问题
现有如下对象数组:
array = [ { 'propertyName1': 'name1', 'propertyValue1': 'value1', 'propertyName2': 'name2', 'propertyValue2': 'value2', 'propertyName3': 'name3', 'propertyValue3': 'value3', 'propertyName4': 'name4', 'propertyValue4': 'value4', }, { 'propertyName1': 'name10', 'propertyValue1': 'value10', 'propertyName2': 'name22', 'propertyValue2': 'value22', 'propertyName3': 'name33', 'propertyValue3': 'value33', 'propertyName4': null, 'propertyValue4': null, } ]
需要将每个元素中propertyNameX的值作为键,propertyValueX的值作为值生成新对象,且不包含值为null的属性。但当前使用的代码会保留null值属性:
ngOnInit() { let obj = {}; this.array.forEach((element: any) => { obj = { ...obj, [element.propertyName1]: element.propertyValue1, [element.propertyName2]: element.propertyValue2, [element.propertyName3]: element.propertyValue3, [element.propertyName4]: element.propertyValue4} } ); console.log(obj); }
原因分析
当前代码直接通过对象展开语法合并所有属性,不管propertyNameX和propertyValueX是否为null,因此null值属性会被保留到最终对象中。
解决方案
方案1:手动判断属性(适用于固定数量的propertyName/Value)
逐个判断每个属性的键和值是否不为null,仅符合条件的属性才会被添加到临时对象,再合并到目标对象:
ngOnInit() { let obj = {}; this.array.forEach((element: any) => { const tempObj = {}; // 仅当键和值都不为null时添加属性 if (element.propertyName1 !== null && element.propertyValue1 !== null) { tempObj[element.propertyName1] = element.propertyValue1; } if (element.propertyName2 !== null && element.propertyValue2 !== null) { tempObj[element.propertyName2] = element.propertyValue2; } if (element.propertyName3 !== null && element.propertyValue3 !== null) { tempObj[element.propertyName3] = element.propertyValue3; } if (element.propertyName4 !== null && element.propertyValue4 !== null) { tempObj[element.propertyName4] = element.propertyValue4; } // 合并临时对象到目标对象 obj = { ...obj, ...tempObj }; }); console.log(obj); }
方案2:通用遍历方式(适用于不固定数量的propertyName/Value)
通过遍历元素的所有属性,自动匹配propertyNameX和对应的propertyValueX,筛选出非null的属性:
ngOnInit() { let obj = {}; this.array.forEach((element: any) => { const tempObj = {}; // 遍历当前元素的所有属性键 Object.keys(element).forEach(key => { // 匹配propertyName开头的键 if (key.startsWith('propertyName')) { const index = key.replace('propertyName', ''); const valueKey = `propertyValue${index}`; const propName = element[key]; const propValue = element[valueKey]; // 仅当键和值都不为null时添加 if (propName !== null && propValue !== null) { tempObj[propName] = propValue; } } }); // 合并到目标对象 obj = { ...obj, ...tempObj }; }); console.log(obj); }
两种方案都会过滤掉null值属性,同时保持原逻辑中“后续元素覆盖前面相同键的值”的行为。
内容的提问来源于stack exchange,提问作者paulotarcio
相关产品推荐
相关产品推荐

