Home > Software design >  How can I create nested JSON Object in Javascript?
How can I create nested JSON Object in Javascript?

Time:01-04

I want to create nested json structure but I couldn't. I want to do as shown in the diagram. some nested sections will be objects and arrays. It's a really difficult and complex schematic so help is needed How can i do this in Javascript

Schema:

{
  "name": "title",
  "img": "image_url",
  "food_kcal": "food_kcal",
  "units": [
    {
      "unit": "test1",
      "data": {
        "amount": "90.0000",
        "calcium": "5.4",
        "calory": "46.8"
      }
    },
    {
      "unit": "test2",
      "data": {
        "amount": "150.0000",
        "calcium": "9.0",
        "calory": "78.0"
      }
    },
    {
      "unit": "test3",
      "data": {
        "amount": "100.0000",
        "calcium": "6.0",
        "calory": "52.0"
      }
    }
  ]
}

My code:

var jsonObj = {
   "food_name":"title",
   "food_image":"image",
   "food_kcal":"kcal_data",
   "units":[]
}; 


for (var i = 0; i < unit_list.length; i  ) { 
   var unit = {};
   var dataObj={};
   unit.food_unit = unit_list[i].text; 
   
   var option = document.getElementsByTagName("option")[i];
   dataObj.amount= option.dataset.amount;
   dataObj.calcium= option.dataset.calcium;
   dataObj.calory= option.dataset.calory;

   jsonObj.units.push(unit);
   jsonObj.units.push(dataObj);
} 


var string = JSON.stringify(jsonObj);
console.log(JSON.parse(string)); 

CodePudding user response:

You should only be pushing one one onto the array each time through the loop, not two. That object should contain unit and dataObj as nested properties.

Change

   jsonObj.units.push(unit);
   jsonObj.units.push(dataObj);

to

jsonObj.units.push({
    unit: unit_list[i].text,
    data: dataObj
}

There's no need for the unit variable.

CodePudding user response:

The issue is because you're pushing the separate values to the array, not an object containing them both.

That being said, the code can be simplified by using map() instead:

// for demo only:
let unit_list = [{ text: 'grams' }, { text: 'kilograms' }, { text: 'mililitres' }];

let obj = {
  food_name: "title",
  food_image: "image",
  food_kcal: "kcal_data",
  units: unit_list.map((item, i) => {
    var option = document.getElementsByTagName("option")[i];
    return {
      food_unit: item.text,
      units: {
        amount: option.dataset.amount,
        calcium: option.dataset.calcium,
        calory: option.dataset.calory        
      }
    }
  })
};

console.log(obj);
<select>
  <option data-amount="1" data-calcium="10" data-calory="100">A</option>
  <option data-amount="2" data-calcium="20" data-calory="200">B</option>
  <option data-amount="3" data-calcium="30" data-calory="300">C</option>
</select>

  •  Tags:  
  • Related