Leonel Matias Domingos
Leonel Matias Domingos

Reputation: 2050

Lodash compare/merge object to array

I need to compare/merge 2 objects with diferent structure using Lodash.

   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"
      },
      .....
    ]

and

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

The question is how i can fill the values of data with the values of dbcolsData ? Lets say put the values of dbColsData in data Thanks in advance

Upvotes: 0

Views: 298

Answers (3)

sebilasse
sebilasse

Reputation: 4618

Reduce data to the dbcolsData structure :

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

->

Now you can use lodash comparison functions like _.isEqual :

_.isEqual(myData, dbcolsData)

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

Use Array#map (or lodash's _.map()) to iterate the data, and get the results from 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);

Upvotes: 0

Keith V
Keith V

Reputation: 730

Try something like this:

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

Upvotes: 1

Related Questions