gpt4 book ai didi

javascript - React javascript - json如何将多个数组元素合并为一个字符串

转载 作者:行者123 更新时间:2023-11-28 14:07:12 25 4
gpt4 key购买 nike

我有一个 JSON 响应,如下所示:

[{
"id": 1,
"food": {
"fruits": ["Banana", "Orange", "Apple", "Mango"],
"veggies": ["greens", "peppers", "carrot", "potatoes"],
}
},
{
"id": 2,
"food": {
"fruits": ["grapes", "berries", "peach", "pears"],
"veggies": ["cabbage", "spinach"],
"dairy": ["nutmilk", "goatmilk"]
}
}
]

现在我想将数组每个“id”(示例中为 1,2)合并到字符串(; 分隔)中,如下所示:

id_1 = Banana;Orange;Apple;Mango;greens;peppers;carrot;potatoes

// observer "id_2" has additional array - "dairy"

id_2 = grapes;berries;peach;pears;cabbage;spinach;nutmilk;goatmilk

键是动态的,因此对于某些记录,有 2 个数组,对于某些记录,它可以是 3 或 4,也可能是 1。

我尝试使用react/Java Script Array.concat(),但我不知道如何动态地执行它。请帮我。谢谢。

最佳答案

使用下面演示的 Object.values().flat().join(';') 可以轻松实现此操作:

let arr=[{"id":1,"food":{"fruits":["Banana","Orange","Apple","Mango"],"veggies":["greens","peppers","carrot","potatoes"],}},{"id":2,"food":{"fruits":["grapes","berries","peach","pears"],"veggies":["cabbage","spinach"],"dairy":["nutmilk","goatmilk"]}}];
const result = arr.map(({id,food}) => ({id, food: Object.values(food).flat().join(';')}));
console.log(result);

您可以轻松地重构输出,只需将其更改为例如[“id_”+id]:Object.values(...)

关于javascript - React javascript - json如何将多个数组元素合并为一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60938530/

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