码迷,mamicode.com
首页 > 其他好文 > 详细

合并 && 还原属性链

时间:2018-08-15 18:32:35      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:[]   sla   ev3   string   etc   item   创建   数据   push   

效果

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

合并 && 还原属性链

标签:[]   sla   ev3   string   etc   item   创建   数据   push   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!