admin管理员组

文章数量:1291041

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

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

Share Improve this question edited Sep 16, 2016 at 15:39 Leonel Matias Domingos asked Sep 16, 2016 at 15:38 Leonel Matias DomingosLeonel Matias Domingos 2,0646 gold badges34 silver badges54 bronze badges 1
  • 2 Please edit the question and add the code you've tried. The can simply be done by looping over array elements and adding key-value pairs to the object. – Tushar Commented Sep 16, 2016 at 15:39
Add a ment  | 

3 Answers 3

Reset to default 9

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
})

本文标签: javascriptConvert array of objects to object using lodashStack Overflow