简体   繁体   中英

Convert array of objects to object using lodash

I have an array of objects that i need to convert to a single object. ex:need to convert

var data=[
  {
    "name": "EMPRESA",
    "value": "CMIP"
  },
  {
    "name": "DSP_DIRECAO",
    "value": "CMIP@040@1900-01-01"
  },
  {
    "name": "DSP_DEPT",
    "value": "CMIP@040@1900-01-01@42@1900-01-01"
  },

... ]

to

   {
    "EMPRESA": "CLCA",
    "DSP_DIRECAO": "CLCA@100@1900-01-01",
    "DSP_DEPT": "CLCA@100@1900-01-01@100@1900-01-01",
    ...
  }

Turn data[x][name] to propertie and data[x][value] to atribute value Thanks

Doesn't use LoDash, but a straight forward reduce()

var obj = data.reduce( (a,b) => {
    return a[b.name] = b.value, a;
}, {});

 var data=[ { "name": "EMPRESA", "value": "CMIP" }, { "name": "DSP_DIRECAO", "value": "CMIP@040@1900-01-01" }, { "name": "DSP_DEPT", "value": "CMIP@040@1900-01-01@42@1900-01-01" } ] var obj = data.reduce( (a,b) => { return a[b.name] = b.value, a; }, {}); console.log(obj); 

Doing the same in LoDash would be something like

var obj = _.transform(data, (a,b) => {
    return a[b.name] = b.value, a;
},{});

On lodash 4.15,

_.chain(data).keyBy("name").mapValues("value").value()

On lodash 3.10,

_.chain(data).indexBy("name").mapValues("value").value()
var newObj = {}
var data = [{
    "name": "EMPRESA",
    "value": "CMIP"
}, {
    "name": "DSP_DIRECAO",
    "value": "CMIP@040@1900-01-01"
}, {
    "name": "DSP_DEPT",
    "value": "CMIP@040@1900-01-01@42@1900-01-01"
}]
data.forEach(function(d) {
    newObj[d.name] = d.value
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM