首页 > 其他 > 详细

合并 && 还原属性链

时间:2018-08-15 18:25:26      阅读:170      评论:0      收藏:0      [点我收藏+]

效果

原数据
{
  "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

合并 && 还原属性链

原文:https://www.cnblogs.com/Lulus/p/9483020.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!