从对象数组内的数组内返回一个值

时间:2018-04-23 07:21:50

标签: javascript arrays



//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);




上面的解决方案有效,但我认为必须有更好的方法从数组内部检索对象,特别是因为我需要运行相同的代码两次...

4 个答案:

答案 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.forEachArray.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);