gpt4 book ai didi

javascript - 根据项目要求将json对象数组解析为特定格式的json数组

转载 作者:行者123 更新时间:2023-11-29 16:31:34 25 4
gpt4 key购买 nike

根据我项目中的要求,我得到以下 json 数组作为输入,但我需要将其转换为特定格式的 json 对象数组。

[
{
"accident_description": "bike accident",
"reported_by": "john",

},
{
"accident_description": "car accident",
"reported_by": "sam",

}
]

输出>>>

  "fields": [
{
"title": "accident_description",
"values": "bike accident"
"type": "generic",

},
{
"title": "reported_by",
"values": "john",
"type": "generic",

},
{
"title": "accident_description",
"values": "car accident"
"type": "generic",

},
{
"title": "reported_by",
"values": "sam",
"type": "generic",

},
]

最佳答案

您可以使用reduce函数来获得所需的输出:-

[
{
"accident_description": "bike accident",
"reported_by": "john",

},
{
"accident_description": "car accident",
"reported_by": "sam",

}
].reduce((arr,item) => {
for(let key in item){
arr.push({
"title" : key,
"values" : item[key],
"type" : "generic"
});
}
return arr;

},[]);

关于javascript - 根据项目要求将json对象数组解析为特定格式的json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55728038/

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