我需要将这个 JSON 扁平化,没有巢,只有贝类,然后是它的名称等。提前致谢!我尝试了一些东西,所以也许可以减少或映射,但我对解决问题的那些东西还不够了解,你们可以分享针对此类问题的任何在线资源吗?我用这些工作很多,掌握起来会很得心应手!
"data": [
{
"name": "Batch1",
"description": "seed",
"age": 2,
"quantity": 1000,
"source": "Hatchery",
"hatchery": "robs hatchery",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade0"
},
"stock_type": {
"name": "seeds"
}
},
{
"name": "Batch2",
"description": "Batch2",
"age": 20,
"quantity": 15700,
"source": "aka",
"hatchery": "aka",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade1"
},
"stock_type": {
"name": "mature"
}
},
{
"name": "5555",
"description": "45",
"age": 1,
"quantity": 134,
"source": "fhh",
"hatchery": "hfhj",
"location": "garden",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade0"
},
"stock_type": {
"name": "seeds"
}
}
]
编辑:我需要这个没有巢,看起来像这样:
"data": [
{
"name": "Batch1",
"description": "seed",
"age": 2,
"quantity": 1000,
"source": "Hatchery",
"hatchery": "robs hatchery",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade0"
},
"stock_type": {
"name": "seeds"
}
},
{
"name": "Batch2",
"description": "Batch2",
"age": 20,
"quantity": 15700,
"source": "aka",
"hatchery": "aka",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade1"
},
"stock_type": {
"name": "mature"
}
},
{
"name": "5555",
"description": "45",
"age": 1,
"quantity": 134,
"source": "fhh",
"hatchery": "hfhj",
"location": "garden",
"shellfish": "oyster",
"grade_list": "Grade0",
"stock_type": "seeds"
}
]
如果您想让数组中的所有元素的这个过程更加自动化,您可以使用 map 来更改所有具有 prop 的元素name
。
const response = {
"data": [
{
"name": "Batch1",
"description": "seed",
"age": 2,
"quantity": 1000,
"source": "Hatchery",
"hatchery": "robs hatchery",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade0"
},
"stock_type": {
"name": "seeds"
}
},
{
"name": "Batch2",
"description": "Batch2",
"age": 20,
"quantity": 15700,
"source": "aka",
"hatchery": "aka",
"location": "dingle",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade1"
},
"stock_type": {
"name": "mature"
}
},
{
"name": "5555",
"description": "45",
"age": 1,
"quantity": 134,
"source": "fhh",
"hatchery": "hfhj",
"location": "garden",
"shellfish": {
"name": "oyster"
},
"grade_list": {
"name": "Grade0"
},
"stock_type": {
"name": "seeds"
}
}
]
}
const result = response.data.map((element) => {
const keysWithNameProp = Object.keys(element).filter(key => element[key].name !== undefined);
const copyOfElement = {...element};
keysWithNameProp.forEach(prop => {
copyOfElement[prop] = element[prop].name;
})
return copyOfElement;
});
console.log(result);
这段代码要做的第一件事是列出所有具有name
道具的键。现在有了这个列表,我可以迭代它并更改对象道具以仅使用name
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句