将对象数组减少到 JS 中的哈希映射

Reducing array of objects to hashmap in JS

您好,我正在尝试将 JSON 数据类型从一种格式转换为另一种格式:

  [ { name: 'CarNo', attributes: {}, children: [], content: '?' },
       { name: 'AccNo', attributes: {}, children: [], content: '?' },
     { name: 'SCS', attributes: {}, children: [], 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;
}, {});

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

在这一行 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);

您可以使用 Object.assign with spread syntax ... and 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);