所以我有这个问题:
我获得了类似这样的数据源
{
"Class": "ScanLayers",
"ExportVersion": 1,
"Layers": {
"0150e77a-9af5-ccc1-aa82-89793c1c4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c539e59019c3",
"Scan": "0150e77a-9af5-4b77-aa82-89793c1c4067",
"ScanName": "ATT021"
},
"0150e77a-9af5-4b77-bb43-89793c1a4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c5sad876adc3",
"Scan": "0150e77a-9af5-4b77-bb43-89793c1a4067",
"ScanName": "ATT022"
}
}
}
我希望能够找到某个扫描名称,然后返回其父级。所以举个例子。我想找"ATT022"
。我会得到"0150e77a-9af5-4b77-bb43-89793c1a4067"
的 UUID 的返回ID我明白如果我有 UUID 这很容易让孩子回来。但我不明白如何找到孩子归还父母。
答案 0 :(得分:2)
使用原生Array.prototype.find从Object.keys(或null
)获取您想要的标准的密钥:
var obj = {
'Class': "ScanLayers",
'ExportVersion': 1,
'Layers': {
"0150e77a-9af5-ccc1-aa82-89793c1c4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c539e59019c3",
"Scan": "0150e77a-9af5-4b77-aa82-89793c1c4067",
"ScanName": "ATT021"
},
"0150e77a-9af5-4b77-bb43-89793c1a4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c5sad876adc3",
"Scan": "0150e77a-9af5-4b77-bb43-89793c1a4067",
"ScanName": "ATT022"
}
}
}
var scanName = "ATT022";
var found = Object.keys(obj.Layers).find(function(layerKey) {
return obj.Layers[layerKey].ScanName == scanName;
});
if (found)
console.log(found);
else
console.log("Nothing found!");
答案 1 :(得分:0)
如果这完全是您的数据模式,您可以使用这样的函数(使用ES6语法):
var obj = {
"Class": "ScanLayers",
"ExportVersion": 1,
"Layers": {
"0150e77a-9af5-ccc1-aa82-89793c1c4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c539e59019c3",
"Scan": "0150e77a-9af5-4b77-aa82-89793c1c4067",
"ScanName": "ATT021"
},
"0150e77a-9af5-4b77-bb43-89793c1a4067": {
"Class": "ScanTiles",
"ExportVersion": 3,
"MetadataUUID": "90a23cdc-9b2f-4788-935d-c5sad876adc3",
"Scan": "0150e77a-9af5-4b77-bb43-89793c1a4067",
"ScanName": "ATT022"
}
}
}
const getIdByScanName = (obj, name) => {
for (id in obj['Layers']) {
if (obj['Layers'][id]['ScanName'] === name) return id
}
}
console.log(getIdByScanName(obj, "ATT021")) //0150e77a-9af5-ccc1-aa82-89793c1c4067
console.log(getIdByScanName(obj, "ATT022")) //0150e77a-9af5-4b77-bb43-89793c1a4067
console.log(getIdByScanName(obj, "ATT023")) //undefined (when key not found)
<小时/> 注意:在您的问题中,
Layers
子对象键之间缺少一个逗号(可能是拼写错误)。
答案 2 :(得分:0)
我为您的问题创建了此jsbin。
你只需要将3个参数传递给这个函数,数据源,类型和字符串
checkName = function (obj,type,string) {
for( var key in obj.Layers){
if(obj.Layers[key][type] === string){
return obj.Layers[key];
}
}
}
console.log(checkName(dataSource,'ScanName','ATT022'))
它会返回这样的东西......
{
Class: "ScanTiles",
ExportVersion: 3,
MetadataUUID: "90a23cdc-9b2f-4788-935d-c5sad876adc3",
Scan: "0150e77a-9af5-4b77-bb43-89793c1a4067",
ScanName: "ATT022"
}