How to put a object inside of a object

Viewed 82

i'm doing a revenue site. So i need to put sections like Fish section, and inside of that section i put some revenues.

So, i initialize a list (list = []), and when the user put the section i put that name on list (e.g. list[0] = {"name" = name}) and add that name to a section.

function showSection() {
      tb = "";

      for (let key in list) {

tb += "<details><summary><h3>" + list[key]["name"] + "</h3></summary>";
        tb += "<input type=\"button\" name=\"addRevenue\" id=\"addRevenue\" value=\"Add revenue\" onclick=\"ask_revenue(" + key + ");\">"
        tb += "<div>List of revenue of the section " + list[key]["name"] + ".</div>"
        tb += "<div id=\"list" + key + "\"></div><br>"
        tb += "</details>";

      }
      document.getElementById("list").innerHTML = tb;
    }

//So after add the section, i want add the revenue with this code:

function addRevenue() {
      var nameRevenue, cost;
      nameRevenue = document.getElementById("name_Revenue").value;
      cost = document.getElementById("cost").value;

      list[indexOfRevenue]["name"] = {
        "nameRevenue": nameRevenue
      }

      list[indexOfRevenue]["name"]["nameRevenue"] = {
        "cost": cost,
      };

      ta += "<div>Name of revenue: " + list[indexOfRevenue]["name"]["nameRevenue"] + ".</div>"
      ta += "<div>Cost: " + list[indexOfRevenue]["name"]["nameRevenue"]["cost"] + ".</div>"
      document.getElementById("list" + indexOfRevenue).innerHTML = ta;
    }

So i expected put into the section, the name of revenue and into the name of revenue put the cost.

And then i can put other revenue into section, and so on and on.

1 Answers

Each item in the array is already an object. You can just specify a new property on that object and set the value.

function addRevenue() {
  var nameRevenue, cost;
  nameRevenue = document.getElementById("name_Revenue").value;
  cost = document.getElementById("cost").value;

  if (list[indexOfRevenue]['revenues'] === undefined) {
    list[indexOfRevenue]['revenues'] = [];
  }

  var revenue = {
    nameRevenue: nameRevenue,
    cost: cost
  };

  list[indexOfRevenue]['revenues'].push(revenue);

  for (var i = 0; i < list[indexOfRevenue]['revenues'].length; i++) {
    var currentRevenue = list[indexOfRevenue]['revenues'][i];
    ta += "<div>Name of revenue: " + currentRevenue.nameRevenue + ".</div>"
    ta += "<div>Cost: " + currentRevenue.cost + ".</div>"
  }


  document.getElementById("list" + indexDaReceita).innerHTML = ta;
}

// Your object looks like this

let obj = [{
  name: 'Tom',
  revenues: [{
    nameRevenue: '600',
    cost: '1000'
  }, {
    nameRevenue: '250',
    cost: '400'
  }]
}];

Related