null 值的处理

85 阅读1分钟
// java后端返回的对象是
const data = {
    a: null,
    b: 1,
    c: null
}
// 前端页面不想显示为 null,想将 null 变为 ''

可以用这个方法:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    const data = {
      a: null,
      b: 1,
      c: null
    }
    const nullToBlank = (data) => {
      Object.keys(data).forEach(item => {
        if (data[item] === null) {
          data[item] = ''
        }
      })
      return data
    }
    // 处理后的 data 值
    // {
    //   "a": "",
    //   "b": 1,
    //   "c": ""
    // }
    console.log(nullToBlank(data));
  </script>
</body>

</html>