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
3 Answers
Reset to default 9Doesn'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
版权声明:本文标题:javascript - Convert array of objects to object using lodash - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741514959a2382830.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论