按对象键值搜索多级javascript数组

时间:2017-01-24 12:49:30

标签: javascript

我有这个对象

  var myObj =   {
    "sections": [{
        "id": "s1",
        "name": "my section no.1",
        "sheets": [{
            "id": "sheet1",
            "questions": [{
                "id": "q1",
                "name": "my q",
                "options": [{
                    "id": "o1",
                    "order_no": 1,
                    "name": "option 1"
                }, {
                    "id": "o2",
                    "name": "option 2"
                }]
            }]
        }]
    }]
};

我希望函数能够通过id搜索这个数组 所以 searchById(“o1”)应该返回

{"id": "o1","order_no": 1,"name": "option 1"}

和searchById(“q1”)应该返回

{
    "id": "q1",
    "name": "my q",
    "options": [{
        "id": "o1",
        "order_no": 1,
        "name": "option 1"
    }, {
        "id": "o2",
        "name": "option 2"
    }]
}

请帮帮我

4 个答案:

答案 0 :(得分:2)

你拥有的是对象,你可以使用map循环创建递归函数来返回结果。



var diagnosticData = [
  { scenario: "Treasury", diagnostic: "good results", action: "Manage Financial Recovery"},
  { scenario: "Treasury", diagnostic: "good results", action: "Analyze the impact of your investments"},
  { scenario: "Treasury", diagnostic: "Significant decline", action: "Ensure an adequate"},
  { scenario: "Treasury", diagnostic: "Significant decline", action: "Pilot your cash"},
  { scenario: "Turnover", diagnostic: "Improve trade efficiency of your business", action: "Valorize your labels"},
  { scenario: "Turnover", diagnostic: "Improve trade efficiency of your business", action: "Analyze the opportunity"},
  { scenario: "Turnover", diagnostic: "Improve trade efficiency of your firm", action: "Contacter un prestataire"}
];


function collectGroupedScenarioDiagnostics(collector, diagnosticItem/*, idx, list*/) {
  var
    scenarioKey           = diagnosticItem.scenario,
    diagnosticKey         = diagnosticItem.diagnostic,

    groupedDiagnosticKey  = [scenarioKey, diagnosticKey].join(' : '),

    scenarioItem          = collector.scenarioStore[scenarioKey],
    groupedDiagnosticItem = collector.diagnosticStore[groupedDiagnosticKey];

  if (!scenarioItem) {
    scenarioItem          = collector.scenarioStore[scenarioKey] = {

      scenario    : scenarioKey,
      diagnostics : []
    };
    collector.diagnosticsList.push(scenarioItem);
  }
  if (!groupedDiagnosticItem) {
    groupedDiagnosticItem = collector.diagnosticStore[groupedDiagnosticKey] = {

      diagnostic: diagnosticKey,
      actions   : []
    };
    scenarioItem.diagnostics.push(groupedDiagnosticItem);
  }
  groupedDiagnosticItem.actions.push(diagnosticItem.action);

  return collector;
}


var groupedScenarioDiagnostics = diagnosticData.reduce(collectGroupedScenarioDiagnostics, {

  scenarioStore   : {},
  diagnosticStore : {},
  diagnosticsList : []

}).diagnosticsList;


console.log('groupedScenarioDiagnostics : ', groupedScenarioDiagnostics);




答案 1 :(得分:1)

谢谢所有这个功能和我一起工作

function findObj(data, id) {
      for (var i in data) {
        if (i == 'id' && data[i] == id) return data;
        if (typeof data[i] == 'object' && findObj(data[i], id)) 
            return  findObj(data[i], id);
        }
     return false;
}

答案 2 :(得分:0)

 myArray =    {
    "sections": [{
        "id": "s1",
        "name": "my section no.1",
        "sheets": [{
            "id": "sheet1",
            "questions": [{
                "id": "q1",
                "name": "my q",
                "options": [{
                    "id": "o1",
                    "order_no": 1,
                    "name": "option 1"
                }, {
                    "id": "o2",
                    "name": "option 2"
                }]
            }]
        }]
    }]
}


 myArray = JSON.parse(myArray).sections;
   function getMeObjById(criteria) {
     var myObj = myArray.filter(funcion(obj){
      if(obj.id !== 'undefined' && obj.id === criteria){
       return true;
      }
     });
     return myObj; // or return myObj[0] if id are unique
    }

答案 3 :(得分:0)

function findID(id, object){
    let _temp;
    // Verify if is Array
    if(object instanceof Array){
        // Scan all objects by doing recursion
        for(let i = 0; i < object.length; i++){
            if((_temp = findID(id, object[i]))){
                return _temp;
            }
        }
    }   

    // Verify if is Object
    if(object instanceof Object){
        // Verify if is the Object ID
        if(object.id && object.id === id){
            return object;
        }
        // Scan all objects by doing recursion
        for(index in object){
            if(object[index] instanceof Object || object[index] instanceof Array){
                if((_temp = findID(id, object[index]))){
                    return _temp;
                }
            }   
        }
    }
}