数据补全(数组对象状态)

已知两个数组对象,将两个id和name合并为一个并且数据都加上(二者合一)

let a= [
    {
        statusDesc: "已发布"
        statusId: "1"
    },
    {
        statusDesc: "认可中",
        statusId: "2"
    },{
        statusDesc: "已完成",
        statusId: "3"
    },{
        statusDesc: "已终止",
        statusId: "4"
    }
]   
let b= [
    {
        count: "1"
        proportion: "17%"
        statusDesc: "已发布"
        statusId: "1"
    },
    {
        count: "9"
        proportion: "17%"
        statusDesc: "认可中"
        statusId: "2"
    },
    {
        count: "6"
        proportion: "17%"
        statusDesc: "已终止"
        statusId: "4"
    },
] 

  方法:两个数组对象合并的方法,合并完按照id进行了排序,返回合并后的数据

// 数组对象合并补全;
  const mergeObject = (objj = {}) => {
    let result = [];
    result = Object.keys(objj)
      .reduce(
        (function (hash) {
          return function (r, k) {
            objj[k].forEach(function (o) {
              if (!hash[o.statusId]) {
                hash[o.statusId] = {};
                r.push(hash[o.statusId]);
              }
              Object.keys(o).forEach(function (l) {
                hash[o.statusId][l] = o[l];
              });
            });
            return r;
          };
        })(Object.create(null)),
        []
      )
      .sort((a, b) => {
        return a['statusId'] - b['statusId'];
      });
    return result;
  };

  调用:

                // 补全状态数据
                    let objj = {
                      part1: a,
                      part2: b
                    };
                    console.log(objj);
                    let aaa = mergeObject(objj); //补全跟状态一直的数据                

  aaa打印出来为二者合并的数据,但是可能存在没有部分属性的情况,比如没有proportion或者count

// 判断是否有属性并且补0
                    for (let i = 0; i < aaa.length; i++) {
                      if (
                        !Object.prototype.hasOwnProperty.call(
                          aaa[i],
                          'count',
                          'proportion'
                        )
                      ) {
                        aaa[i].count = '0';
                        aaa[i].proportion = '0%';
                      }
                    }

  判断数组对象内数据是否含有某个属性,没有加上补0

打印aaa,就是一个完整的数据

例子数据:

数组一:

 

数组二:

 

 

 合并补0后:

 

posted @ 2022-07-22 17:37  Ao_min  阅读(145)  评论(0编辑  收藏  举报