【问题标题】:Reducing array of objects to hashmap in JS在JS中将对象数组减少为hashmap
【发布时间】:2017-10-02 12:19:28
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reduce


    【解决方案1】:

    你的想法是对的,但这里是如何做到的:

    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

    【讨论】:

      【解决方案2】:

      您可以将Object.assignspread syntax ...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);

      【讨论】:

        【解决方案3】:

        通过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);

        【讨论】:

          猜你喜欢
          • 2018-05-30
          • 2017-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-02
          • 2018-07-18
          • 1970-01-01
          相关资源
          最近更新 更多