我有一个未知的结构化 JSON 对象,我想读取其所有属性并在条件匹配时返回其值。
{
"tags": ["a", "b", "c"],
"image": "path/to/thumbnail.png",
"description": "First level description",
"name": "First name",
"another": {
"abcde": {
"label": "one two three",
"description": "Oopsy!"
},
"fghijk": {
"label": "Label ABC :)",
"description": "Is not a song here bruh!"
}
},
"couldBeEmpty": {},
"couldBeLast": {
"someCoolName": {
"label": "Some label here you know",
"description": "Another Desc Again",
"type": "text"
},
"someLabelAgain": {
"label": "Just a label name",
"description": "Yep another Desc :)",
"type": "color"
},
"someObjLabel": {
"label": "Another label name",
"description": "Desc label here too",
"type": "text"
},
"ahCoolThing": {
"label": "Some label for this too",
"description": "Desc here is fine too",
"type": "color"
},
"couldBeLastInHere": {
"label": "label",
"description": "Desc goes here",
"type": "color"
}
}
}
我想获取对象的任何给定结构的所有名称、标签和描述,然后创建一个新对象像这样
{
"description": "First level description",
"name": "First name",
"abcde/label": "one two three",
"abcde/description": "Oopsy!"
"fghijk/label": "Label ABC :)",
"fghijk/description": "Is not a song here bruh!"
"someCoolName/label": "Some label here you know",
"someCoolName/description": "Another Desc Again",
"someLabelAgain/label": "Just a label name",
"someLabelAgain/description": "Yep another Desc :)",
"someObjLabel/label": "Another label name",
"someObjLabel/description": "Desc label here too",
"ahCoolThing/label": "Some label for this too",
"ahCoolThing/description": "Desc here is fine too",
"couldBeLastInHere/label": "label",
"couldBeLastInHere/description": "Desc goes here"
}
现在我正在尝试使用 Lodash为此,但无法找到一种方法来查找具有给定名称的所有属性,除非必须循环遍历所有内容
最佳答案
您正在寻找的本质上是一个自定义缩减函数(您正在尝试将对象缩减为其数据的某种压缩表示)。这是一个允许您指定要提取哪些字段的实现:
function myReduce(o, fields, p, c) {
// p: path
// c: context (accumulator)
if(p===undefined) p = '', c = {};
for(var prop in o) {
if(!o.hasOwnProperty(prop)) continue;
if(fields.indexOf(prop)!=-1) c[p + prop] = o[prop];
else if(typeof o[prop]==='object') myReduce(o[prop], fields, prop + '/', c);
}
return c;
}
要获取您感兴趣的字段,您可以这样调用它:
myReduce(data, ['name', 'label', 'description']);
关于javascript - 在对象中查找匹配的属性名称并返回其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24320050/