[英]How to extract deeply nested array of objects and move to React Hook state?
[英]How to extract both deeply and shallowly nested fields in array of json objects
假设我有这个 json 对象:
{
"lotOfJson": [
{
"value": "someName",
"property": "name",
"children": [],
"constraints": {
"IsValidName": "name someName isn't valid"
}
},
{
"value": [
{
"id": "firstBadId"
},
{
"id": "secondBadId"
}
],
"property": "listOfIds",
"children": [
{
"value": {
"id": "firstBadId"
},
"property": "0",
"children": [
{
"value": "firstBadId",
"property": "id",
"children": [],
"constraints": {
"badIdError": "This Id is bad!"
}
}
]
},
{
"value": {
"id": "secondBadId"
},
"property": "1",
"children": [
{
"value": "secondBadId",
"property": "id",
"children": [],
"constraints": {
"badIdError": "This Id is bad"
}
}
]
}
]
}
]
}
这个数组可以有很深的嵌套 JSON——没有办法知道有多深。
每当有一个块看起来像:
"value": "",
"property": "",
"children": [],
"constraints": {
"": ""
}
我想提取value
、 property
和constraints
value
并将它们保存在一个数组中。 对于我上面的"lotsOfJson"
示例,这看起来像: ["someName", "name", "name SomeName isn't valid", "firstBadId, "id", "This Id is bad!", "secondBadId, "id", "This Id is bad!"]
所以我只在它们平行时提取值、属性和约束,就像在上面的块中一样。
例如,我可以使用迭代器不可知地提取 JSON 数组中的所有value
、 property
和constraints
,但是有没有办法仅在它们彼此平行时提取它们?
您可以使用for...in
循环为此创建递归函数,并且仅当当前对象在children
数组中没有元素时才添加到结果中。
const data = [{"value":"someName","property":"name","children":[],"constraints":{"IsValidName":"name someName isn't valid"}},{"value":[{"id":"firstBadId"},{"id":"secondBadId"}],"property":"listOfIds","children":[{"value":{"id":"firstBadId"},"property":"0","children":[{"value":"firstBadId","property":"id","children":[],"constraints":{"badIdError":"This Id is bad!"}}]},{"value":{"id":"secondBadId"},"property":"1","children":[{"value":"secondBadId","property":"id","children":[],"constraints":{"badIdError":"This Id is bad"}}]}]}] function extract(data, fields) { let result = [] for (let i in data) { if (typeof data[i] == 'object') { result.push(...extract(data[i], fields)) } if (data.children && !data.children.length) { if (fields.includes(i)) { result = result.concat( typeof data[i] == 'object' ? Object.values(data[i]) : data[i] ) } } } return result; } const result = extract(data, ['property', 'value', 'constraints']) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.