我有一个这样的对象:
var structure = {
"root":{
"name":"Main Level",
nodes:{
"node1":{
"label":"Node 1"
},
"node2":{
"label":"Node 2",
"selected": true
},
"node3":{
"label":"Node 3"
}
}
}
}
在javascript中如何在对象中搜索选中:true',并获取其上方的标签值,即"节点2"
答案 0 :(得分:1)
您想要使用for循环。
var nodes = structure.roots.nodes;
var nodeYouWant;
for (var obj in nodes){
if (nodes[obj].selected == true){
nodeYouWant = obj; // Now "node2"
}
}
答案 1 :(得分:1)
您可以遍历structure.root.nodes
的密钥(可以使用Object.keys
获取)并检查该密钥的节点对象是否为selected
。出于本演示的目的,我只记录了选定的node.label
。
var structure = {
"root": {
"name": "Main Level",
nodes: {
"node1": {
"label": "Node 1"
},
"node2": {
"label": "Node 2",
"selected": true
},
"node3": {
"label": "Node 3"
}
}
}
}
var nodes = structure.root.nodes,
keys = Object.keys(nodes)
for (var i = 0; i < keys.length; i++) {
var node = nodes[keys[i]]
if (node.selected) {
console.log("Selected:", node.label)
break;
}
}
&#13;
答案 2 :(得分:1)
for (n in structure.root.nodes) {
if (structure.root.nodes[n].selected) {
console.log("the node which is selected is: " + n);
}
}
答案 3 :(得分:0)
这将以递归方式遍历您的对象,查找所选值,如果找到则返回密钥名称。
const structure = {
"root": {
"name": "Main Level",
nodes: {
"node1": {
"label": "Node 1"
},
"node2": {
"label": "Node 2",
"selected": true
},
"node3": {
"label": "Node 3"
}
}
}
}
const findSelected = (obj, ret = '') => {
for (let key in obj) {
if (obj[key].selected) {
return key
}
if (obj[key].constructor === Object) {
ret = findSelected(obj[key])
if (ret) return ret
}
}
}
console.log(
findSelected(structure)
)
&#13;
答案 4 :(得分:0)
也许你可以尝试以下方式。
var structure = {
"root": {
"name": "Main Level",
nodes: {
"node1": {
"label": "Node 1"
},
"node2": {
"label": "Node 2",
"selected": true
},
"node3": {
"label": "Node 3"
}
}
}
};
let nodes = structure.root.nodes;
Object.keys(nodes).forEach(key => {
if(nodes[key].selected === true){
//do something like below
//console.log(nodes[key].label);
}
});
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys