//Structure
const definitions = {
sections: [
{ title: 'Section A', actions: [ { id: 0, name: 'action A' } ] },
{ title: 'Section B', actions: [ { id: 1, name: 'action B' } ] },
]
};
//Code to retrieve the action
const id = 1;
const sectionDef = definitions.sections.find(s => s.actions.find(a => a.id === id));
const actionDef = sectionDef.actions.find(a => a.id === id);
//Print it
console.log(actionDef);

上面的解决方案有效,但我认为必须有更好的方法从数组内部检索对象,特别是因为我需要运行相同的代码两次...
答案 0 :(得分:1)
您可以使用递归方法,使用对象的所有值在任意数据结构中进行搜索。
function find(object, key, value) {
var result;
if (object[key] === value) {
return object;
}
if (object && typeof object === 'object') {
Object.values(object).some(o => result = find(o, key, value));
}
return result;
}
var definitions = { sections: [{ title: 'Section A', actions: [{ id: 0, name: 'action A' }] }, { title: 'Section B', actions: [{ id: 1, name: 'action B' }] }] };
console.log(find(definitions, 'id', 0));
console.log(find(definitions, 'id', 1));

答案 1 :(得分:1)
您可以使用Array.forEach
和Array.find
//Structure
const definitions = {
sections: [
{ title: 'Section A', actions: [ { id: 0, name: 'action A' } ] },
{ title: 'Section B', actions: [ { id: 1, name: 'action B' } ] },
]
};
//Code to retrieve the action
const id = 1;
let action;
definitions.sections.forEach(section => {
action = section.actions.find(a => a.id === id);
});
//Print it
console.log(action);

答案 2 :(得分:0)
您的代码在const sectionDef = definitions.find
上有错误,因为它应该是const sectionDef = definitions.sections.find
,因为find
适用于数组类型。你正在做的事情很好,可以达到预期的效果。
const definitions = {
sections: [
{ title: 'Section A', actions: [ { id: 0, name: 'action A' } ] },
{ title: 'Section B', actions: [ { id: 1, name: 'action B' } ] },
]
}
const id = 1;
const sectionDef = definitions.sections.find(s => s.actions.find(a => a.id === id));
const actionDef = sectionDef.actions.find(a => a.id === id);
console.log(sectionDef);
console.log(actionDef);

答案 3 :(得分:0)
const definitions = {
sections: [
{ title: 'Section A', actions: [ { id: 0, name: 'action A' } ] },
{ title: 'Section B', actions: [ { id: 1, name: 'action B' } ] },
]
}
const id = 1;
var result2;
var data = definitions.sections;
var result = data.filter(function(obj) {
var data2 = obj.actions;
result2 = data2.filter(function(obj) {
return obj.id == id;
});
});
console.log(result2);