当 JavaScript 数组中的对象包含 itemValue 属性,且其值为 [] 或空字符串时,我们可以使用 map 方法将其设置为 null

以下是实现方法:

arr = arr.map(item => {
  if (item.itemValue === [] || item.itemValue === '') {
    item.itemValue = null;
  }
  return item;
});

这段代码首先使用 map 方法对 arr 数组进行遍历,处理每个对象。对于每个对象,判断其 itemValue 是否为 [] 或空字符串,如果是则将其赋值为 null,否则不做修改。最后返回修改后的对象。这样就可以将 arr 数组中所有 itemValue[] 或空字符串的对象的 itemValue 属性都设置为 null 了。

示例:

let arr = [{
  customizeId: 200,
  itemLabel: '姓名',
  itemType: '1',
  itemValue: '何俊'
}, {
  customizeId: 202,
  itemLabel: '兴趣爱好',
  itemType: '6',
  itemValue: '[篮球]'
}, {
  customizeId: 203,
  itemLabel: '年龄段',
  itemType: '5',
  itemValue: '21~25岁'
}, {
  customizeId: 204,
  itemLabel: '图片上传',
  itemType: '3',
  itemValue: []
}];

arr = arr.map(item => {
  if (item.itemValue === [] || item.itemValue === '') {
    item.itemValue = null;
  }
  return item;
});

console.log(arr);

输出:

[{
  'customizeId': 200,
  'itemLabel': '姓名',
  'itemType': '1',
  'itemValue': '何俊'
}, {
  'customizeId': 202,
  'itemLabel': '兴趣爱好',
  'itemType': '6',
  'itemValue': '[篮球]'
}, {
  'customizeId': 203,
  'itemLabel': '年龄段',
  'itemType': '5',
  'itemValue': '21~25岁'
}, {
  'customizeId': 204,
  'itemLabel': '图片上传',
  'itemType': '3',
  'itemValue': null
}]

通过这段代码,我们可以将数组中 itemValue[] 或空字符串的对象的 itemValue 属性设置为 null,方便后续处理和使用。

JavaScript数组处理:将空值或空数组的itemValue属性设置为null

原文地址: https://www.cveoy.top/t/topic/oLNw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录