[英]Reducing array of objects to hashmap in JS
嗨,我正在尝试将JSON数据类型从一种格式转换为另一种格式:
[ { name: 'CarNo', attributes: {}, children: [], content: '?' },
{ name: 'AccNo', attributes: {}, children: [], content: '?' },
{ name: 'SCS', attributes: {}, children: [], content: '?' }]
目标对象将基于name属性和content属性:
{'CarNo': '?', 'AccNo': '?', 'SCS': '?' }
我当时以为我可以减少这种情况,但我失败了:
const filteredResponseObj = Object.keys(rawResponseBodyObj).reduce((p,c)=>{
if( c === 'name' ){
p[c]=rawResponseBodyObj[c].content;
}
return p;
},{});
我想念什么? 显然我在减少方面存在一些问题...
您有正确的主意,但以下是操作方法:
const filteredResponseObj = rawResponseBodyObj.reduce(function(map, obj) {
map[obj.name] = obj.content;
return map;
}, {});
您可以将Object.assign
与扩展语法...
和Array#map
来生成对象。
var array = [{ name: 'CarNo', attributes: {}, children: [], content: '?' }, { name: 'AccNo', attributes: {}, children: [], content: '?' }, { name: 'SCS', attributes: {}, children: [], content: '?' }], result = Object.assign(...array.map(o => ({ [o.name]: o.content }))); console.log(result);
使用c === 'name'
这行代码,您试图将初始数组中的对象与字符串name
。 这样的比较将永远给false
正确的方法应如下所示:
var arr = [ { name: 'CarNo', attributes: {}, children: [], content: '?' }, { name: 'AccNo', attributes: {}, children: [], content: '?' }, { name: 'SCS', attributes: {}, children: [], content: '?' }], filtered = arr.reduce(function (r, o) { if (!r[o.name]) r[o.name] = o['content']; return r; }, {}); console.log(filtered);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.