简体   繁体   English

展平深度嵌套的对象数组

[英]Flatten deeply nested array of objects

I have following array of objects我有以下对象数组

 { "_id": "63c6cd09c4836daca5a8ea51", "groupBy": "Title Metadata", "name": "Search Title Name", "tooltip": "Searches for books based on title input", "renderNATypes": false, "isFrequentlyUsed": true, "childFilters": [ { "_id": "63c6cd09c4836daca5a8ea1f", "controlType": { "name": "inputbox" }, }, { "_id": "63c6cd09c42136daca5a8ea1f", "controlType": { "name": "dropdown" }, } ] } ]

Output I am expecting is new array with number of child with child properties and also parent property Output 我期待的是新数组,其中包含具有子属性和父属性的子项数量

 [{ "_id": "63c6cd09c4836daca5a8ea51", "child_id": "63c6cd09c4836daca5a8ea1f" "groupBy": "Title Metadata", "name": "Search Title Name", "tooltip": "Searches for books based on title input", "renderNATypes": false, "isFrequentlyUsed": true, "controlType": {"name": "inputbox"} }, { "_id": "63c6cd09c4836daca5a8ea51", "child_id": "63c6cd09c42136daca5a8ea1f" "groupBy": "Title Metadata", "name": "Search Title Name", "tooltip": "Searches for books based on title input", "renderNATypes": false, "isFrequentlyUsed": true, "controlType": {"name": "dropdown"}, } ]

I have tried lodash flatMap, flatMapDeep and few more vanilla javascript without any success.我已经尝试过 lodash flatMap、flatMapDeep 和其他几个 vanilla javascript,但都没有成功。

Thanks in advance提前致谢

You can achieve your result by using reduce like this您可以像这样使用reduce来实现您的结果

 const flattenByChildFilters = (orig) => orig.reduce((item, cur) => { const {childFilters, ...base} = cur; const newItems = childFilters.map(({controlType}) => ({...base, controlType, })); cur = [...item, ...newItems]; return cur; }, []); console.log(flattenByChildFilters([ { _id: '63c6cd09c4836daca5a8ea51', groupBy: 'Title Metadata', name: 'Search Title Name', tooltip: 'Searches for books based on title input', renderNATypes: false, isFrequentlyUsed: true, childFilters: [ { _id: '63c6cd09c4836daca5a8ea1f', controlType: { name: 'inputbox', }, }, { _id: '63c6cd09c42136daca5a8ea1f', controlType: { name: 'dropdown', }, }, ], }, ]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM