在JS中将对象数组减少为hashmap

时间:2017-05-04 10:52:15

标签: javascript reduce

您好我正在尝试将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;
        },{});

我错过了什么?显然我对减少有一些问题...

3 个答案:

答案 0 :(得分:2)

你有正确的想法,但这是如何做到的:

const filteredResponseObj = rawResponseBodyObj.reduce(function(map, obj) {
    map[obj.name] = obj.content;
    return map;
}, {});

使用Convert object array to hash map, indexed by an attribute value of the Object

答案 1 :(得分:1)

您可以将Object.assignspread syntax ...Array#map一起用于生成对象。

Expression

答案 2 :(得分:0)

使用此行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);

相关问题