Lodash比较/合并对象到数组

时间:2017-12-13 13:58:57

标签: javascript arrays object lodash

我需要使用Lodash比较/合并具有不同结构的2个对象。

   data= [
      {
        "name": "EMPRESA",
        "value": ""
      },
      {
        "name": "DESIGEMPRESA",
        "value": "CMIP"
      },
      {
        "name": "UTILIZADOR",
        "value": ""
      },
      {
        "name": "CD_INDICADOR",
        "value": ""
      },
      {
        "name": "DT_INI_INDICADOR",
        "value": ""
      },
      {
        "name": "DT_INI",
        "value": "2017-12-13"
      },
      .....
    ]

dbcolsData={
  "EMPRESA": "",
  "UTILIZADOR": "paulo.figueiredo",
  "CD_INDICADOR": "",
  "DT_INI_INDICADOR": "",
  "DT_INI": "",
  "DT_FIM": ""
}

问题是我如何使用dbcolsData的值填充data的值? 让我们说dbColsData的值data 提前致谢

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

_.forEach(data, function(object){
   object.value = dbcolsData[object.name];
})

答案 1 :(得分:0)

使用Array#map(或lodash的_.map())来迭代data,并从dbcolsData获取结果:

var data = [{"name":"EMPRESA","value":""},{"name":"DESIGEMPRESA","value":"CMIP"},{"name":"UTILIZADOR","value":""},{"name":"CD_INDICADOR","value":""},{"name":"DT_INI_INDICADOR","value":""},{"name":"DT_INI","value":"2017-12-13"}];

var dbcolsData = {"EMPRESA":"","UTILIZADOR":"paulo.figueiredo","CD_INDICADOR":"","DT_INI_INDICADOR":"","DT_INI":"","DT_FIM":""};

var result = data.map(function(o) {
  return Object.assign({ data: dbcolsData[o.name] }, o);
});

console.log(result);

答案 2 :(得分:0)

data缩减为dbcolsData结构:

var myData = data.reduce((o, nvO) => Object.defineProperty(o, nvO.name, {value: nvO.value}), {})

- >

现在您可以使用lodash比较功能,例如_.isEqual

_.isEqual(myData, dbcolsData)