如何从对象中的子对象获取父键

  • 本文关键字:对象 获取 javascript
  • 更新时间 :
  • 英文 :


给定一个对象,我想从子对象开始获得父键。因为我只关心键,所以我从条目迭代,但它总是返回未定义。

var book = {
"chapter1": {
"paragraph1": {
"text": "..."
},
"paragraph2": {
"text": "..."
}
},
"chapter2": {
"paragraph3": {
"text": "..."
},
"paragraph4": {
"text": "..."
}
},
"chapter3": {
"paragraph5": {
"text": "..."
},
"paragraph6": {
"text": "..."
}
}
};

var section = "paragraph3";
const category = Object.entries(book).find(([, e]) => Object.values(e).includes(section)); /// should return chapter2
if (category) {
console.log(category[0], category[1]);
} else {
console.log("Not Found");
}

只需将代码中的.values()替换为.keys():

var book =  {
"chapter1": {
"paragraph1": {
"text": "..."
},
"paragraph2": {
"text": "..."
}
},
"chapter2": {
"paragraph3": {
"text": "..."
},
"paragraph4": {
"text": "..."
}
},
"chapter3": {
"paragraph5": {
"text": "..."
},
"paragraph6": {
"text": "..."
}
}
};

var section = "paragraph3";
const category = Object.entries(book).find(([, e]) => Object.keys(e).includes(section)); /// should return chapter2
if (category) {
console.log(category[0], category[1]);
} else {
console.log("Not Found");
}

这是一个如何从子节点获取父键的解决方案

var book = {
chapter1: {
paragraph1: {
text: '...'
},
paragraph2: {
text: '...'
}
},
chapter2: {
paragraph3: {
text: '...'
},
paragraph4: {
text: '...'
}
},
chapter3: {
paragraph5: {
text: '...'
},
paragraph6: {
text: '...'
}
}
};
var section = 'paragraph3';
const category = Object.entries(book).find(e =>
Object.keys(e[1]).includes(section)
); /// should return chapter2
if (category) {
console.log(category[0]);
} else {
console.log('Not Found');
}

最新更新