[英]Convert nested [Array] of {Object} to > {Object} | JSON File
I am new to JSON data manipulation and I would like some help.我是 JSON 数据操作的新手,我需要一些帮助。
I have a JSON file that looks like the below:我有一个如下所示的 JSON 文件:
[
{
"plannification": {
"Data": 1,
"DataType": "GB",
"InclusionOption1": ".",
"Default": false,
"PropositionId": "GBT13456",
"EssentialLink": "greatpdf.com/pdf.pdf",
"Term": "1",
"Segment": "part",
"Id": "653284",
}
},
{
"plannification": {
"Data": 1,
"DataType": "FR",
"inclusionOption1": ".",
"default": false,
"PropositionId": "FRT13456",
"EssentialLink": "greatpdf.com/pdf2.pdf",
"term": "1",
"Segment": "pro",
"Id": "984532",
}
}
]
I'd like to to convert this file to object and only pull data from "Segment": “pro”,
as below:我想将此文件转换为对象,并且只从
"Segment": “pro”,
提取数据"Segment": “pro”,
如下所示:
{
984532:{
Segment: "pro",
EssentialLink: "greatpdf.com/pdf.pdf",
PropositionId: "FRT13456",
},
etc.. {},
}
Where do I start?我从哪里开始?
You can filter your array using array#filter
on the Segment
where the value is pro
.您可以在值为
pro
的Segment
上使用array#filter
过滤您的数组。 You can use array#reduce
and iterate through the array and using Object#values()
take out the values of each object and create your new object.您可以使用
array#reduce
并遍历数组并使用Object#values()
取出每个对象的值并创建新对象。
const data = [{ "plannification": { "Data": 1, "DataType": "GB", "InclusionOption1": ".", "Default": false, "PropositionId": "GBT13456", "EssentialLink": "greatpdf.com/pdf.pdf", "Term": "1", "Segment": "part", "Id": "653284" } }, { "plannification": { "Data": 1, "DataType":"FR", "inclusionOption1": ".", "default": false, "PropositionId": "FRT13456", "EssentialLink": "greatpdf.com/pdf2.pdf", "term": "1", "Segment": "pro", "Id": "984532", } } ], result = data.filter(o => { let { Segment } = Object.values(o)[0]; return Segment === 'pro'; }).reduce((r,o) => { let { Id, Segment, PropositionId, EssentialLink } = Object.values(o)[0]; r[Id] = { Segment, PropositionId, EssentialLink }; return r; },{}) console.log(result);
1 - Read the json file 1 - 读取 json 文件
2 - Iterate over the array of objects 2 - 迭代对象数组
3 - For every object, check your desired property 3 - 对于每个对象,检查您想要的属性
4 - If it matchs what you want, read the properties of the object and construct your object 4 - 如果它符合您的要求,请读取对象的属性并构建您的对象
您的数据结构无效,首先更正您编写 json 对象数组的方式,以便我可以弄清楚
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.