gpt4 book ai didi

javascript - 使用 Javascript 基于 Key Substring 将动态对象转换为多级 JSON 数组

转载 作者:搜寻专家 更新时间:2023-11-01 04:28:43 24 4
gpt4 key购买 nike

我想基于 Key Substring 从平面动态对象创建多级 JSON 数组

示例动态对象

{
Honda_Bike: "white",
Pulsar_Bike: "black",
Royal_Enfield_Bike: "red",
Hyundai_Car: "blue",
Mercedes_Car: "grey",
BMW_Car: "red"
}

示例 Json 多级数组

[{
vehicle : {
bike: {
Honda_Bike: "white",
Pulsar_Bike: "black",
Royal_Enfield_Bike: "red"
},
car: {
Hyundai_Car: "blue",
Mercedes_Car: "grey",
BMW_Car: "red"
},
}
}]

最佳答案

使用 reduce 迭代输入对象的条目以检查项目并将其分类为所需的输出格式:

const input = {
Honda_Bike: "white",
Pulsar_Bike: "black",
Royal_Enfield_Bike: "red",
Hyundai_Car: "blue",
Mercedes_Car: "grey",
BMW_Car: "red"
};
const output = [{ }];
output[0].vehicle = Object.entries(input).reduce((a, [key, val]) => {
const vehicleName = key.match(/([^_]+)$/)[0];
if (!a[vehicleName]) a[vehicleName] = {};
a[vehicleName][key] = val;
return a;
}, {});
console.log(output);

关于javascript - 使用 Javascript 基于 Key Substring 将动态对象转换为多级 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50266392/

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