gpt4 book ai didi

javascript - 根据现有值重新排列 JSON 值

转载 作者:行者123 更新时间:2023-12-02 23:29:15 26 4
gpt4 key购买 nike

提供的 JSON 是一种非结构化的,不符合我的很多要求 要求。我已经尝试了很多方法,但确实需要很长时间 当我提供 100,000 条记录时

实现的代码

for (var f in stack.data) {
var field = new Object();
for (var o in stack.data[f]['field_values']) {
field[stack.data[f]['field_values'][o]['field_name']] = stack.data[f]['field_values'][o]['value'];
}
stack.data[f]['field_values'] = field;
}
console.log(JSON.stringify(stack, null, 2));

输入 JSON:

var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",

"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}

预期输出:

{
"data": [
{
"id": 950888888073,
"name": "www.stackoverflow.com",
"field_values": {
"Newsletter?": true,
"Parent": "Gigi Hallow",
"Birthday": "2018-04-29",
"Related": "2012-00121-Sass",
"Referral": "Don Ho",
"Spouse": "Wo Fat"
}

有时“field_values 可能为空。也需要检查它们

     {
"id": 950821118875,
"name": "www.google.com",
"field_values": [],
}

这主要是重新排列值。在这里,值变成了键。实际上应该有一个类轮来处理这个问题,但我已经没有选择了。

希望问题很清楚

最佳答案

声明一个变量来保存数组元素可能会有所帮助,而不是每次循环时都进行 4 级索引。您还可以使用解构来提取对象的属性。

并使用 {} 而不是 new Object

即使这不会提高性能,也会使代码更易于阅读。

var stack = {
"data": [{
"id": 950888888073,
"name": "www.stackoverflow.com",

"field_values": [{
"field_name": "Newsletter?",
"value": true
},
{
"field_name": "Parent",
"value": 950888661
},
{
"field_name": "Birthday",
"value": "2018-04-29"
},
{
"field_name": "Related matter",
"value": 1055396205
},
{
"field_name": "Referral",
"value": "Don Ho"
},
{
"field_name": "Spouse",
"value": "Wo Fat"
}
]
}]
}

for (var f in stack.data) {
const field = {};
const fobj = stack.data[f];
for (var o in fobj.field_values) {
const {field_name, value} = fobj.field_values[o];
field[field_name] = value;
}
fobj.field_values = field;
}

console.log(JSON.stringify(stack, null, 2));

关于javascript - 根据现有值重新排列 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56584105/

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