节点和父链接

时间:2019-04-25 19:05:51

标签: windows socket.io async-await

我有json集合,该集合包含作为数组或键值对的嵌套元素,并且可以嵌套到任意长度。我需要通过一个数组,找到其中的项目,然后将它们转换为各自的值。

例如,在下面的给定数组中,我有一个数组

一个仅获取值的函数 1.我将传递此数组以查找JSON集合中的这两个单元,并将它们转换为值。这些值可以在树中的任何位置。我需要拾取单元格及其父节点。并且应该搜索它们并在其中输入各自的值,以便将其从[“ TRC030-A”,“ TRSEE050-A”]更改为[22,12]

一个仅用于汇总值的函数 2.请注意有集合,并且其中的单元格相同。但如果我在示例中通过了“ NSEE050-A”,“ NSEE060-A”,则应选择它们并将其值相加并加起来

我需要递归执行此javascript。 问候

{   
"MusicVersion": "1.0.0",
"validationVersion": "1.0.0",
"submissionStage": "editing / submitted for approval etc.",
"PiaonoData": { 
         "musicacademies": [
           {
              "name": "Music Name",
            }]
 },
"MainData": { 
  },
  }

1 个答案:

答案 0 :(得分:-1)

您可以使用Map将搜索数组中的键映射到同一数组中的索引。该映射将允许快速检查数据中的属性是否与任何属性匹配并给出其索引。它也可以与indexOf一起使用,但是Map更快。

其余是递归函数:找到所有键后即可退出:

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"]));