javascript - JSON.stringify() 以便对象字段位于一行
问题描述
我需要将从服务器获取的数据导出为 .txt 文件
我得到的结构是这样的:
{
"value": {
"name": "A",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false,
"fixed": true
},
"children": [
{
"value": {
"name": "Aa",
"mandatory": false,
"contentMandatory": true,
"multipleAllowed": false,
"mergeStrategy": {
"_type": "PrioritizedSourceStrategy"
},
"fixed": false
},
"children": [
{
"value": {
"name": "Aaa",
"mandatory": false,
"contentMandatory": false,
"multipleAllowed": true,
"fixed": false
},
"children": [
{
"value": {
"name": "AaaA",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false,
"fixed": false
},
"children": []
}
]
},
{
"value": {
"name": "AaB",
"mandatory": false,
"contentMandatory": false,
"multipleAllowed": true,
"fixed": false
},
"children": [
{
"value": {
"name": "AaBa",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false,
"fixed": false
},
"children": []
}
]
}
]
}
...
}
]
}
但我需要结构在文件中看起来像这样:
"name": "A", "mandatory": true, "contentMandatory": true, "multipleAllowed": false,
"name": "Aa", "mandatory": false, "contentMandatory": true, "multipleAllowed": false, "mergeStrategy": { "_type": "PrioritizedSourceStrategy"}
"name": "Aaa", "mandatory": false, "contentMandatory": false, "multipleAllowed": true,
"name": "AaaA", "mandatory": true, "contentMandatory": true, "multipleAllowed": false,
"name": "AaB", "mandatory": false, "contentMandatory": false, "multipleAllowed": true,
"name": "AaBa", "mandatory": true, "contentMandatory": true, "multipleAllowed": false,
...
所以我需要删除一些对象字段(如“固定”)并显示每个对象一行中留下的字段。存档此结果的最佳方法是什么?
解决方案
您想要的结构是错误的,因为您有重复的属性。如果这是您想要的结构:
{
"name": "A",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false,
"children": [
{
"name": "Aa",
"mandatory": false,
"contentMandatory": true,
"multipleAllowed": false,
"mergeStrategy": { "_type": "PrioritizedSourceStrategy" },
"children": [
{
"name": "Aaa",
"mandatory": false,
"contentMandatory": false,
"multipleAllowed": true,
"children": [
{
"name": "AaaA",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false
}
]
},
{
"name": "AaB",
"mandatory": false,
"contentMandatory": false,
"multipleAllowed": true,
"children": [
{
"name": "AaBa",
"mandatory": true,
"contentMandatory": true,
"multipleAllowed": false
}
]
}
]
}
]
}
然后使用此代码段:
var parsedObject = parse(obj)
function parse(obj) {
let children = obj.children.map(child => parse(child))
return { name, mandatory, contentMandatory, multipleAllowed, mergeStrategy, children } = {...obj.value, children}
}
我正在使用地图和对象解构来保留我想要的属性。
推荐阅读
- python - DataFrame 行的多条件搜索返回空结果
- php - 未采取 Gmail 操作的 PHPMailer
- c++ - 编译 GLFW 代码时参数无效?
- ios - iOS 视频缓存 - 手动缓存删除
- automated-tests - 空手道 - 输入字段/文本区域清除字段无法正常工作
- javascript - 我可以在条件下使用正则表达式吗?我如何为以辅音开头的单词和以 Javascript 中以元音开头的单词做条件
- filtering - 高级标签过滤不适用于同一集合中选择的多个标签
- python - 在分隔符上拆分 pandas df 行,然后根据索引重命名另一行
- php - Laravel 6 无域名路由
- javascript - 如何从 Typescript 中的字典对象中获取匹配值?