原數據 { "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; }
示例代碼git