-1

I am trying to fetch an array inside the multiple objects as stored in MongoDB. when I perform a get method from node js I get "path" and "content". "path" gives the property name in a strig.

Here is the data:

 content:{
          'abc':{
            'def':{
              'ghi':{
                'jklm.pd':[...]  //this is the content i need to fetch
              },
              'lmn':{
                  'rst':{
                  'opqr.pd': [...] //this is the content i need to fetch
                 }
              }
            }
          }...
        },
        path:["/abc/def/ghi/jklm.pd",
              "/abc/def/lmn/rst/opqr.pd"
                  ......] 

based on each path I need to get the array from the content. need to do this in node.js please help me with this

santosh
  • 192
  • 9
  • `content.abc.def.ghi['jklm.pd']`...it is much better not to use any dots in your attribute names – messerbill Sep 15 '19 at 18:41
  • Please give me an example – santosh Sep 15 '19 at 19:08
  • Possible duplicate of [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Jared Smith Sep 15 '19 at 20:07
  • Possible duplicate of [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Ulysse BN Sep 16 '19 at 22:56

1 Answers1

1

We can use String.split() to split path values to access each property individually.

Then we can access the content for each path and store the result in an array.

var content = {
  'abc': {
    'def': {
      'ghi': {
        'jklm.pd': ["a", "b"] //this is the content i need to fetch
      },
      'lmn': {
        'rst': {
          'opqr.pd': ["c", "d"] //this is the content i need to fetch
        }
      }
    }
  },
  'path': ["/abc/def/ghi/jklm.pd",
    "/abc/def/lmn/rst/opqr.pd"
  ]
};

var result = [];

content.path.forEach(path => {
  // Splitting by '/' character and filtering empty characters.
  var properties = path.split('/').filter(item => item.trim() !== '');

  var value = content;

  for (let property of properties) {
    value = value[property];
  }

  console.log(value);

  result.push(value); // Storing in an array.
});
Nikhil
  • 6,493
  • 10
  • 31
  • 68