我如何在单个键值对数组中获取嵌套的json对象值

时间:2019-09-24 12:40:38

标签: javascript typescript

我已经嵌套了json对象数组,我想从该嵌套数组中获取单个键值对格式的值,以传递给http调用,而不是我需要数组的单个对象

[{
   "menu_id":1,
   "parent_menu_id":0,
   "children":[
      {
         "menu_id":2,
         "parent_menu_id":1,
         "children":[
            {
               "menu_id":3,
               "parent_menu_id":2,
               "children":[

               ]
            }
         ]
      }
   ]
},
{
   "menu_id":5,
   "parent_menu_id":0,
   "children":[
      {
         "menu_id":6,
         "parent_menu_id":5,
         "children":[
            {
               "menu_id":7,
               "parent_menu_id":6,
               "children":[

               ]
            }
         ]
      }
   ]
}]

我需要数组格式的结果

[
   {
      "menu_id":1,
      "parent_menu_id":0
   },
   {
      "menu_id":2,
      "parent_menu_id":1
   },
   {
      "menu_id":3,
      "parent_menu_id":2
   }
]

1 个答案:

答案 0 :(得分:1)

您可以为此创建一个递归函数。

function toFlatArray(obj) {
  let result = [];
  result.push({
    menu_id: obj.menu_id,
    parent_menu_id: obj.parent_menu_id
  });
  if (obj.children && obj.children.length) {
      obj.children.forEach(child => {
        result = result.concat(toFlatArray(child));
      });
  }
  return result;
}

// added another method to run forEach
function toFlatArrayFromArray(arr) {
  let result = [];
  arr.forEach(obj => {
    result = result.concat(toFlatArray(obj));
  });

  return result;
}

const myObj = [{
  "menu_id":1,
  "parent_menu_id":0,
  "children":[
    {
        "menu_id":2,
        "parent_menu_id":1,
        "children":[
          {
              "menu_id":3,
              "parent_menu_id":2,
              "children":[

              ]
          }
        ]
    }
  ]
},
{
  "menu_id":5,
  "parent_menu_id":0,
  "children":[
    {
        "menu_id":6,
        "parent_menu_id":5,
        "children":[
          {
              "menu_id":7,
              "parent_menu_id":6,
              "children":[

              ]
          }
        ]
    }
  ]
}];

console.log(toFlatArrayFromArray(myObj));