【HarmonyOS】JSON格式化解析Map数据失败

发布时间 2023-11-23 11:36:39作者: Mayism123
【关键字】

数据转换、JSON.stringify、Object.fromEntries

 

【问题背景】

将数组转换成Map对象,然后调用let str = JSON.stringify(newMap),将Map转换成字符串,转换出来的结果是{}

问题代码:

let data = [
          { key: 'where', value: '何地'},
          { key: 'when', value: '何时'},
          { key: 'why', value: '何因'},
       ]
let newMap = new Map<string,string>()
data.forEach((item) => {
        newMap.set(item.key,item.value)
  })
let str = JSON.stringify(newMap)
console.info(str+'newMap')

cke_2414.png

 

【解决方案】

先用Object.fromEntries将Map转为object再进行转换就可以了 

let data = [
          { key: 'where', value: '何地'},
          { key: 'when', value: '何时'},
          { key: 'why', value: '何因'},
       ]
let newMap = new Map<string,string>()
data.forEach((item) => {
        newMap.set(item.key,item.value)
  })
let str = JSON.stringify(Object.fromEntries(newMap))
console.info(str+'newMap')

cke_10450.png

逆转换可参考Object.entries方法。

 

【参考文档】

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries