gpt4 book ai didi

javascript - 如何使用 Lodash 在 Typescript 中展平我的示例对象?

转载 作者:行者123 更新时间:2023-11-28 14:15:08 24 4
gpt4 key购买 nike

我需要展平输入 json 并使用相同的键合并对象。预期对象的结构如下例所示:

{
"error": {
"group1": {
"mapping":
[{"0": "mapping1"},
{"1": "mapping1"}],
"other":
[{"0": "other0"}]
},
"group2": {
"mapping":
[{"0": "mapping2"},
{"1": "mapping2"}]

}
}
}

所以我想摆脱组并仅保留组的子代类型。输出应该是:

{
"error": {
"mapping":
[{"0": "mapping1"},
{"1": "mapping1"},
{"0": "mapping2"},
{"1": "mapping2"}]
"other":
[{"0": "other0"}]
}
}

我是 JavaScript 新手,这是我的代码,我相信它可以做得更好:

function flattenReport(obj) {
var reports = Object.keys(obj.error)
for (report in reports) {
var pos = obj.error[reports[report]]
var types = Object.keys(pos)
for (type in types) {
var pos1 = pos[types[type]]
var elements = Object.keys(pos1)
for (element in elements) {
if (types[type] in obj.error) {
obj.error[types[type]].push(pos1[element])
}
else {
obj.error[types[type]] = []
obj.error[types[type]].push(pos1[element])
}
}
}
}
return obj
}

我认为 Lodash 会帮助缩短这个时间

编辑:我忘记在函数末尾删除组

最佳答案

Lodash 可以简单地解决这个问题:

let x= {
"error": {
"group1": {
"mapping":
[{"0": "mapping1"},
{"1": "mapping1"}],
"other":
[{"0": "other0"}]
},
"group2": {
"mapping":
[{"0": "mapping2"},
{"1": "mapping2"}]

}
}
}

let result = {"error":
_.mergeWith({},..._.map(x['error'],v=>v),(o, s)=>(o||[]).concat(s))
}

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

关于javascript - 如何使用 Lodash 在 Typescript 中展平我的示例对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57863066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com