Вы можете использовать Map
для сопоставления ключей в вашем поисковом массиве с их индексом в том же массиве.Эта карта позволит быстро проверить, соответствует ли свойство в данных какому-либо свойству, и дать его индекс.Он также будет работать с indexOf
, но карта быстрее.
В остальном это рекурсивная функция: ее можно завершить, как только будут найдены все ключи:
function mapKeys(obj, keys) {
const map = new Map(keys.map((key, i) => [key, i]));
const result = [];
function recur(obj) {
for (prop in obj) {
if (Object(obj[prop]) === obj[prop]) {
recur(obj[prop]);
} else if (map.has(prop)) {
result[map.get(prop)] = obj[prop];
map.delete(prop);
if (!map.size) return;
}
}
}
recur(obj);
return result;
}
// Sample data
const data = {"MusicVersion": "1.0.0","validationVersion": "1.0.0","submissionStage": "editing / submitted for approval etc.","PiaonoData": {"musicacademies": [{"name": "Music Name","id": "Music ID / UPIN","data": "See Example Form Object","SCI040": "newly admitted member"}]},"MainData": {"mainBalance": {"CAATOT" : 0,"AFC020-A": 11,"TRC030-A": 22,"TRC040-A": 33,},"nonMainData": {"TRSEE050-A": 12,"staffEmoluments" : [{"NSEE050-A": 12,"NSEE050-B": 22,"NSEE050-C": 40,"NSEE050-D": 54},{"NGEE050-A": 36,"NGEE050-B": 41,"NGEE050-C": 9,"NGEE050-D": 0},{"NLEE050-A": 1,"NLEE050-B": 3,"NLEE050-C": 7,"NLEE050-D": 9}],"MuiscSpecialPayments": [{"LSRP010-A": 12,"LSRP010-B": 22,"LSRP010-C": 40,"LSRP010-D": 54},{"LDSP010-A": 36,"LDSP010-B": 41,"LDSP010-C": 9,"LDSP010-D": 0},{"LDSP010-A": 1,"LDSP010-B": 3,"LDSP010-C": 7,"LSSP010-D": 9}],"MusicConversions": [{"type": "simple/complex/conversion","TATI010-A": 1,"TATI010-B": 3,"TATI020-A": 7,"TATI030-B": 9}]}},"MusicData": {"AatOverview": { "TATI010-A": 1,"ABCD": 3,"DEF": 7,"KLM": 9},"acOverview": {"TATI010-A": 1,"ATAATI010-B": 3,"OPQ": 7,"ATAATI030-B": 9,},"musicacademies": [{"name": "Music Name","id": "MusicID","data": "See Example Form Object","MCI040": "Newly admitted"}]},"otherMusicData": { "tbc": null },"MusicCompletionStatuses": { "tbc": null },"MusicValidationExplanations": {"ABC1001": {"fieldValue": "600","userComment": "Extra spend"},"ABS1196": {"fieldValue": "30","userComment": "This is the reason "}},"lastUpdatedBy": "user namer","lastUpdatedDate": "2016-04-23T18:25:43.511Z"};
console.log(mapKeys(data, ["TRC030-A", "NSEE050-A"]));