我有一个复杂的结构,我需要根据某些条件进行遍历和转换;这是一个应该涵盖大多数场景的结构(简短)示例:
{ PROP1: {
metadata: Object, // somewhere deeper in metadata I have a `value` key
parent: { $ref: String },
employee: {
parent: { $ref: String },
id: String,
metadata: Object,
products: {
metadata: Object,
model: { $ref: String },
type: 'array',
value: ["String", "String" , "String"] ,
[...]
},
model: {
id: String,
email: {
metadata: Object,
value: 'a@b.com',
type: 'string',
validity: Object,
[...]
},
name: {
firstName: {
metadata: Object,
value: 'John',
type: String,
validity: Object,
[...]
},
lastName: {
metadata: Object,
value: 'Smith',
type: String,
validity: Object,
[...]
},
}
},
operations: {
id: String,
items: [
{ action: {value: "UPDATE", model: {$ref: String }, [...] },
{...}
],
metadata: Object,
[...]
}
}
},
PROP2: {
// similar as PROP1
},
[... and so on ...]
}
我基本上需要在将它发送到后端之前将其清理干净;
$ref
时,我都不想要键/值对(例如:PROP1.parent是没用的,可以省略)value
,我就需要省略其他所有内容,并将value
的值移动为key
的值(例如:PROP1.employee.products应该等于[& #39; String',' String',' String'])id
,metadata
,validity
(等)等关键字无论其内容如何都可以完全省略所以最终结果应该是那些:
{ PROP1: {
employee: {
products: ['item','item','item'],
model: {
email: 'a@b.com',
name: { firstName: 'John', lastName: 'Smith'},
},
operations: [
{action: 'UPDATE'}
]
}
},
PROP2: { ... }
}
我使用不同的lodash
方法尝试了很多不同的方法,但无法绕过这个方法......
非常感谢任何帮助
由于
答案 0 :(得分:0)
在伪代码中,尝试这样的事情。当您遇到麻烦时,实施细节并发布更多信息。
var ignoreKeyArray = ["id", ...] // keys to ignore and remove
var newJSON = "{}";
for (property in JSON) {
var newProp = parseJSON(key, property);
insert newProp in newJSON object
}
var parseJSON = function (key, jsonBlob) {
if (key in ignoreKeyArray || jsonBlob contains value "$ref")
return "";
var jsonOut = key + ": {}";
for (child in jsonBlob) {
add parseJSON(child) to jsonOut;
}
return jsonOut;
}
如果您有任何问题,请发表评论,以便我可以延长答案并澄清。