Skip to content
Advertisement

How can I access multiply nested sub objects in javascript?

I have a larger code which handles and sorts data. In it I want to work with objects to keep it easier and better structured. I have multiple categories and all of them have different nested subobjects, which I have trouble accessing writing/reading. I searched on the web, w3schools but couldn’t find my mistake, so sry for this entry level question!

I wrote a test function to better understand objects!

function test(){
  var report, time, name, date, value;
  report = 'Income Statement';
  time = 'Annually';
  name = 'Revenue';
  date = '2017';
  value = '10000000';
  data = {}
  data[report] = {}
  data[report][time] = {}
  data[report][time][name] = {}
  data[report][time][name][date] = value;
  console.log(data);
}

As to my understanding what this code does is: -create an empty object data -create an empty subobject report -create an empty subsubobject time -create an empty subsubsubobject name -gives the subsubsubobject name a key/value pair date:value (at least that was my intention to do)

First I tried to skip creating empty objects and directly fill data{} with: data = {} data[report][time][name][date] = value; but he seems to cannot set properties to this. So I created like above coded first empty subobjects for all subcategories, is this really necessary or am I falling for a simple syntax mistake?

However he still doesn’t log me the desired output which would be:

{ 'Income Statement': { Annually: { Revenue: {2017:10000000} } } }

and instead gives me:

{ 'Income Statement': { Annually: { Revenue: [Object] } } }

Simply put.. what am I doing wrong? 😀

Thanks in advance for any kind of help! Best regards

Advertisement

Answer

I don’t think you are doing anything wrong. I pasted same code in JS console and it is giving proper result.

Screenshot of console with result of function

Different ways to initialize object

  • Static Data

let data = {
  'Income Statement': {
    'Annually': {
      'Revenue': {
        '2017': '10000000'
      }
    }
  }
}

document.querySelector("#data-result").innerHTML = JSON.stringify(data)
<div id="data-result"></div>
  • Dynamic Data

var report, time, name, date, value;
report = 'Income Statement';
time = 'Annually';
name = 'Revenue';
date = '2017';
value = '10000000';

let data = {
  [report]: {
    [time]: {
      [name]: {
        [date]: value
      }
    }
  }
}

document.querySelector("#object-result").innerHTML = JSON.stringify(data)
<div id="object-result"></div>

You can also consider different ways to store same data.

Example –

let data = [{
  report: 'Income Statement'
  time: 'Annually'
  name: 'Revenue'
  date: '2017'
  value: '10000000'
}]

So now, if you want data by date in future you can get that by using filter

let data_2017 = data.filter(x => x.date === '2017');
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement