获取多个对象内的数组

时间:2019-09-15 18:38:04

标签: javascript node.js

我试图获取存储在MongoDB中的多个对象内部的数组。当我从节点js执行get方法时,我得到“路径”和“内容”。 “路径”以strig给出属性名称。

以下是数据:

 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"
                  ......] 

基于每个路径,我需要从内容中获取数组。需要在node.js中执行此操作,请帮助我

1 个答案:

答案 0 :(得分:1)

我们可以使用String.split()拆分path值来分别访问每个属性。

然后,我们可以访问每个路径的内容并将结果存储在数组中。

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.
});