gpt4 book ai didi

javascript - Node : How to restructure nested JSON data getting and organize reusable?

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:32 26 4
gpt4 key购买 nike

使用 Node 请求模块,我通过 URL 获取 JSON 数据。 JSON 文件嵌套在多个级别中,并且未以可重复使用的方式进行组织。当前的 JSON 如下所示:

{
"data": {
"series": {
"brochure_image": "range.jpg",
"background_image": "range.jpg",
"Model 1": {
"medium_images": "Model_1.png",
"brand": "Tesla",
"Model 101": {
"medium_images": "Model_101.png",
"brochure_image": "Model_101.png",
},
"Model 102": {
"medium_images": "Model_102.png",
"brochure_image": "Model_102.png",
}
},
"Model 2": {
"medium_images": "Model_2.png",
"brand": "Tesla",
"Model 201": {
"medium_images": "Model_201.png",
"brochure_image": "Model_201.png",
}
}
}
}
}

我想进行重组,以便可以轻松地从前端访问数据。我想这样改变:

[
{
"series":"Model 1",
"model": [
{
"modelName": "Model 101",
"medium_images": "Model_101.png",
"brochure_image": "Model_101.png"
},
{
"modelName": "Model 102",
"medium_images": "Model_102.png",
"brochure_image": "Model_102.png"
}
]
}
{
"series":"Model 2",
"model": [
{
"modelName": "Model 201",
"medium_images": "Model_101.png",
"brochure_image": "Model_101.png"
}
]
}
]

我该怎么做?我的 Node server.js 获取部分如下所示:

const dataUrl = "http://example.com/data/series-data.json";

// API
app.get("/api/getSeriesData", (req, res) => {
request.get(dataUrl, (error, response, body) => {
var json = JSON.parse(body);
var seriesObj = json.data.series;
var seriesArr = [];

for (var series in seriesObj) {

if (seriesObj.hasOwnProperty(series)) {
seriesArr.push({"series": series, "model": seriesObj[series]});
}
}
res.send(seriesArr);
});
});

最佳答案

你可以这样做:

var obj = {
"data": {
"series": {
"brochure_image": "range.jpg",
"background_image": "range.jpg",
"Model 1": {
"medium_images": "Model_1.png",
"brand": "Tesla",
"Model 101": {
"medium_images": "Model_101.png",
"brochure_image": "Model_101.png",
},
"Model 102": {
"medium_images": "Model_102.png",
"brochure_image": "Model_102.png",
}
},
"Model 2": {
"medium_images": "Model_2.png",
"brand": "Tesla",
"Model 201": {
"medium_images": "Model_201.png",
"brochure_image": "Model_201.png",
}
}
}
}
};

var result = [];
Object.keys(obj.data.series).forEach(key => {
if(key.indexOf("Model") === 0){
var o = {series: key, model:[]};
Object.keys(obj.data.series[key]).forEach(k => {
if(k.indexOf("Model") === 0){
o.model.push({modelName: k, medium_image: obj.data.series[key][k].medium_image, brochure_image: obj.data.series[key][k].brochure_image});
}
});
result.push(o);
}
});

console.log(result);

它的作用是循环遍历 .data.seriesdata.series[MODEL NAME] 的所有属性,并仅考虑属性名称以 Model 开头的值。如果并非您感兴趣的所有值的属性名称都以 Model 开头,则此方法将不起作用。在这些情况下,您可能必须使用否定断言(检查它们的属性名称是否不是您不感兴趣的已知名称之一)。

关于javascript - Node : How to restructure nested JSON data getting and organize reusable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47494067/

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