javascriptjsonkey-value

Get all the values of a particular key from Json file


[
   {
      "id":"0001",
      "type":"donut",
      "name":"Cake",
      "ppu":0.55,
      "batters":{
         "batter":[
            {
               "id":"1001",
               "type":"Regular"
            },
            {
               "id":"1002",
               "type":"Chocolate"
            }
         ]
      },
      "topping":[
         {
            "id":"5002",
            "type":"Glazed"
         }
         {
            "id":"5004",
            "type":"Maple"
         }
      ]
   },
   {
      "id":"0002",
      "type":"donut",
      "name":"Raised",
      "ppu":0.55,
      "batters":{
         "batter":[
            {
               "id":"1001",
               "type":"Regular"
            }
         ]
      },
      "topping":[
         {
            "id":"5003",
            "type":"Chocolate"
         },
         {
            "id":"5004",
            "type":"Maple"
         }
      ]
   },
   {
      "id":"0003",
      "type":"donut",
      "name":"Old Fashioned",
      "ppu":0.55,
      "batters":{
         "batter":[
            {
               "id":"1001",
               "type":"Regular"
            },
            {
               "id":"1002",
               "type":"Chocolate"
            }
         ]
      },
      "topping":[
         {
            "id":"5001",
            "type":"None"
         },
         {
            "id":"5004",
            "type":"Maple"
         }
      ]
   }
]

Expected output: [donut, Regular, Chocolate, Glazed, Maple, donut, Regular, Chocolate, Maple, donut, Regular, Chocolate, None, Maple]

Get all values of key(type) from above JSon into an array, including all children. Attached is the sample json and also expected output. Is there any _lodash function for this or any Javascript function is also fine.


Solution

  • I think you need a recursive function for extract all values by key.

    function extractValuesByKey(obj, field) {
      if (!obj) return [];
      if (typeof obj !== "object") return [];
      if (Array.isArray(obj))
        return obj.map((value) => extractValuesByKey(value, field)).flat();
    
      let result = [];
      Object.keys(obj).forEach((key) => {
        if (key === field) result.push(obj[key]);
        else result = result.concat(extractValuesByKey(obj[key], field));
      });
      return result;
    }