Javascript 将对象结构简化为仅包含特定属性的值

Javascript 将对象结构简化为仅包含特定属性的值,javascript,lodash,Javascript,Lodash,假设某事物与给定的下列对象相似: const foo = { id: 'foo', name: '...', test: () => 'fn', nestedObject: { id: 'nested', name: '...', nestedObjects: [{ id: 'bar', name: '...', anotherNested: { id: 'n1', name: '.

假设某事物与给定的下列对象相似:

const foo = {
  id: 'foo',
  name: '...',
  test: () => 'fn',
  nestedObject: {
    id: 'nested',
    name: '...',
    nestedObjects: [{
      id: 'bar',
      name: '...',
      anotherNested: {
        id: 'n1',
        name: '...',
        oneMoreNestedObjects: [{
          id: 'n11',
          name: '...',
        }, {
          id: 'n12',
          name: '...',
        }]
      }
    }, {
      id: 'bar2',
      name: '...',
    }]
  }
};
我只想通过拾取名称为
id
的属性,或者如果它是具有id属性的对象(数组),将其转换为对象。因此,在我的示例中,它将是:

const result = {
  id: 'foo',
  nestedObject: {
    id: 'nested',
    nestedObjects: [{
      id: 'bar',
      anotherNested: {
        id: 'n1',
        oneMoreNestedObjects: [{
          id: 'n11',
        }, {
          id: 'n12',
        }]
      }
    }, {
      id: 'bar2',
    }]
  }
};

顺便说一句:我对使用lodash很在行。

你想过使用递归吗?请注意,对于深度对象,这可能会超过最大调用堆栈

  function getIdsFromObjects(nObj) {
    return Object.keys(nObj).reduce(function (curr, next) {
      if (next === 'id') {
        curr[next] = nObj[next]
      }
      if (Array.isArray(nObj[next])) {
        curr[next] = nObj[next].map(function(mapObj) {
          return getIdsFromObjects(mapObj)
        })
      }
      if (typeof obj[next] === 'object' && !Array.isArray(nObj[next])) {
         curr[next] = getIdsFromObjects(nObj[next])
      }
      return curr;
    },{})
  }

console.log(JSON.stringify(getIdsFromObjects(foo), null, 4))

对于嵌套数组和对象,可以使用迭代递归方法

函数过滤器(对象){
返回Object.keys(Object).reduce(函数r,k){
如果(k=='id'){
r[k]=对象[k];
}else if(对象[k]&&typeof对象[k]='object'){
r[k]=过滤器(对象[k]);
}
返回r;
},Array.isArray(对象)?[]:{};
}
var foo={id:'foo',name:'…',test:()=>'fn',nestedObject:{id:'nested',name:'…',nestedObjects:[{id:'bar',name:'…',另一个nestedObjects:{id:'n1',name:',},{id:'n12',name:',}},{,
结果=过滤器(foo);
控制台日志(结果)

.as控制台包装{max height:100%!important;top:0;}
thx-我刚刚添加了递归级别+删除空值的限制: