javascript - 如何获取具有嵌套属性的 Javascript 对象的子集?

标签 javascript arrays angular typescript object

我正在使用 Angular 进行开发,我有以下 Typescript 对象数组:

docs = [
    { 
        id: '1',
        type: {
            id: 1
            desc: 'Category 1',
        }
        title: 'Foo",
        date: '2018-06-21',
        attachments: [
            { id: 51, filename: 'foo.pdf', title: 'Foo' },
            { id: 20, filename: 'bar.doc', title: 'Bar' }
        ]
    },
    { 
        id: '2',
        type: {
            id: 2
            desc: 'Category 2',
        }
        title: 'Bar",
        date: '2018-06-21',
        attachments: [
            { id: 15, filename: 'foobar.xls', title: 'Foobar' },
            { id: 201, filename: 'example.doc', title: 'Example' }
        ]
    }
]

我只需要获取一部分属性,如下所示:

docs = [
    { 
        id: '1',
        type: {
            id: 1
            desc: 'Category 1',
        }
        attachments: [
            { id: 51 },
            { id: 20 }
        ]
    },
    { 
        id: '2',
        type: {
            id: 2
            desc: 'Category 2',
        }
        attachments: [
            { id: 15 },
            { id: 201 }
        ]
    }
]

我怎样才能做到这一点? 我是否需要创建解析器或是否存在任何智能方式(例如 Lodash)来提取数组的精简版?

最佳答案

var docs = [{"id":"1","type":{"id":1,"desc":"Category 1"},"title":"Foo","date":"2018-06-21","attachments":[{"id":51,"filename":"foo.pdf","title":"Foo"},{"id":20,"filename":"bar.doc","title":"Bar"}]},{"id":"2","type":{"id":2,"desc":"Category 2"},"title":"Bar","date":"2018-06-21","attachments":[{"id":15,"filename":"foobar.xls","title":"Foobar"},{"id":201,"filename":"example.doc","title":"Example"}]}];

const result = docs.map(({id,type,attachments})=>{
    let doc={id,type};
    doc.attachments=attachments.map(({id})=>({id}));
    return doc;
});

console.log(result);

看看这个。这非常有效!

关于javascript - 如何获取具有嵌套属性的 Javascript 对象的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50971127/

相关文章:

angular - ng2-smart-table 在编辑单击时打开弹出窗口

javascript - Node 服务器下载图片成功但不显示

javascript - socketIO 数据未定义

javascript - Angular、karma/jasmine 测试不处理 .bind

c# - 数组赋值蛇

c - Typedefed 数组类型不可分配

javascript - 对象、数组或类数组对象

Angular(5) - 延迟加载和 canActivate 守卫 - StaticInjectorError

javascript - OpenLayers 仅在鼠标移动结束后才具有重绘功能

angular - 如何在 Angular 中创建动态菜单