gpt4 book ai didi

javascript - 向 JSON 对象添加方括号

转载 作者:行者123 更新时间:2023-12-01 01:15:12 25 4
gpt4 key购买 nike

我从我的服务器获取此 JSON。但要使用此 JSON,我需要向 MH 对象添加方括号。我怎样才能做到这一点。我尝试了 .map 但我没有让它为我工作。有没有更好的解决办法。或者在那里使用 .map 。如果是的话,你能告诉我如何做到这一点的提示吗?或者有更好的解决方案吗?

{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": {
"MHVSS1": [
{}
],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": {
"MHVSS1": [
{}
],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
}
]
}

我需要这个带有方括号的 JSON 围绕 MH 对象

{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": [{
"MHVSS1": [
{}
],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}]
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": [{
"MHVSS1": [
{}
],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
]}
]
}

最佳答案

这并不是真正的“添加方括号”,而是将“MH”对象包装在数组中。

无论如何,这里有一个 .map 语句可以为您完成此操作(不会改变原始数据,因此出现 Object.assign 恶作剧):

data.PAD = data.PAD.map((padObj) => Object.assign({}, padObj, {MH: [padObj.MH]}));

基本上,对于 PAD 数组中的每个条目,我们都会合并其中的三个对象:

  • 一个新的空对象{}
  • 原始 padObj 条目
  • 一个小对象,仅将原始 padObj 中的 MH 元素封装在数组中。

输出符合预期:

{
"PAD": [
{
"PADPS286": "Dampf",
"PADPS124": "Hans",
"PADPS60": "2018-05-01",
"PADPS143": "1",
"MH": [
{
"MHVSS1": [{}],
"MHDIRW214": 2017,
"MHDIRW215": 2018,
"birthdate": "2018-05-01",
"MHDIRW129 ": "0"
}
]
},
{
"PADPS286": "Snow",
"PADPS124": "Jon",
"PADPS60": "2077-05-01",
"PADPS143": "",
"MH": [
{
"MHVSS1": [{}],
"MHDIRW214": 4,
"MHDIRW215": 4,
"birthdate": "2077-05-01",
"MHDIRW129 ": "0"
}
]
}
]
}

关于javascript - 向 JSON 对象添加方括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54823669/

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