2 回答
TA贡献1846条经验 获得超7个赞
映射数组,并_.mapValues()在每个对象上使用。对于每个作为数组且充满值的null值,返回'empty':
const array = [{"id":123,"name":"Peter","phone":[null,null],"addresses":[{"address1":"Manchester, UK","address2":"London, UK"}]},{"id":124,"name":"Sara","phone":[],"addresses":[{"address1":"London, UK","address2":"Paris, FR"}]}];
const result = array.map(o =>
_.mapValues(o, v => // map the values of the object
_.isArray(v) && v.every(_.isNull) ? 'empty' : v // if a value is an array, and all values are null return 'empty'
)
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
TA贡献1810条经验 获得超4个赞
首先循环遍历数组,在每个对象中,您可以设置电话属性:
for(const entry of array) {
const isEmpty = entry.phone.filter(p => p !== null).length === 0;
entry.phone = isEmpty ? 'empty' : entry.phone;
}
需要注意的是,这会编辑您的数组。对问题前提的一个担忧是您将数组属性设置为字符串,这并不理想。
现场示例:https ://jsfiddle.net/michaschwab/9ze3p2or/3/,这是您编辑的堆栈闪电战: https ://stackblitz.com/edit/null-nested-array-into-string-jwhfwn
如果你不想修改你的数组,这是一种方法:
const modified = array.map(entry => {
return {...entry, // Copy previous values
phone: entry.phone.filter(p => p !== null).length === 0 ? 'empty' : entry.phone
};
});
添加回答
举报