1. 程式人生 > >合並 && 還原屬性鏈

合並 && 還原屬性鏈

git tle chains ast -c 代碼 i++ 組織 效果

效果

原數據
{
  "id": 10,
  "text": {
    "title": "title",
    "content": "content"
  },
  "image": {
    "url": "image url",
    "name": "image name",
    "size": "900KB"
  }
}
1.還原(拆解)屬性鏈
[
  {
    "key": "id",
    "value": 10
  },
  {
    "key": "text.title",
    "value": "title"
  },
  {
    "key": "text.content",
    "value": "content"
  },
  {
    "key": "image.url",
    "value": "image url"
  },
  {
    "key": "image.name",
    "value": "image name"
  },
  {
    "key": "image.size",
    "value": "900KB"
  }
]
2.合並屬性鏈
{
  "id": 10,
  "text": {
    "title": "title",
    "content": "content"
  },
  "image": {
    "url": "image url",
    "name": "image name",
    "size": "900KB"
  }
}

關鍵代碼

// 合並屬性鏈
Merge(items): any {
    var res = {}    
    for (let i = 0; i < items.length; i++) {
        var item = items[i];
        // key
        var prochains: string[] = item.key.split(‘.‘);//屬性鏈
        var tmpObj = res;
        //組織屬性
        for (let i = 0; i < prochains.length; i++) {
            const pro = prochains[i];        
            var islast = i == prochains.length - 1;
            //沒有屬性就創建為obj
            if (!tmpObj.hasOwnProperty(pro)) {
                tmpObj[pro] = {}
            }
            else {
                //檢查一下,如果已經有屬性了, 並且現在不是最後一個屬性, 那麽這個地方應該是obj,不是的話說明屬性鏈有問題
                if(typeof tmpObj[pro]!=="object"&&!islast){
                    tmpObj[pro] = {}            
                }
            }
            //屬性鏈最後一個要賦值
            if (islast) {
                // value
                tmpObj[pro] = item.value;
            }
            //屬性下鉆
            tmpObj = tmpObj[pro]
        }
    }
    return res;
}
// 還原屬性鏈
objPro2ProDic(obj, dic, root) {
    if (!dic) {
        dic = [];
    }
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const ele = obj[key];
            if (typeof ele === "object" && !(ele instanceof Array)) {
                //下鉆
                this.objPro2ProDic(ele, dic,key)
            }
            else{
                var _key = root?`${root}.${key}`:key;
                // 這裏返回key-value
                dic.push({
                    key:_key,
                    value:ele
                });
            }
        }
    }
    return dic;
}

示例代碼

https://github.com/zLulus/NotePractice/tree/dev3/Website/DotNetCore/CoreAngular/src/app/name-chains

合並 && 還原屬性鏈