Find by key deep in a nested array

后端 未结 17 1581
礼貌的吻别
礼貌的吻别 2020-11-22 15:41

Let\'s say I have an object:

[
    {
        \'title\': \"some title\"
        \'channel_id\':\'123we\'
        \'options\': [
                    {
                 


        
17条回答
  •  猫巷女王i
    2020-11-22 16:00

    This piece of code allows you to get all objects within a JSON whose key is user-defined.

    function main(obj = {}, property){
     const views = [];
    
     function traverse(o) {
        for (var i in o) {
          if(i === property) views.push(o[i]);
          if (!!o[i] && typeof(o[i])=="object") {
            console.log(i, o[i]);
            traverse(o[i]);
          } else {
            console.log(i, o[i]);
          }
        }
        }
    
      traverse(obj);
      return views;
    
    }
    
    
    
    

    Here is an example:

    const obj = {
        id: 'id at level 1',
        level2: {
          id: 'id at level 2',
          level3: {
            id: 'id at level 3',
            level4: {
              level5: {
                id: 'id at level 5'
              }
           }
        }
      },
      text: ''
    }
    
    main(obj, 'id');
    
    

提交回复
热议问题