将对象数组减少到 JS 中的 hashmap [英] Reducing array of objects to hashmap in JS

查看:37
本文介绍了将对象数组减少到 JS 中的 hashmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I am trying to transform a JSON data type from one format to another:

  [ { name: 'CarNo', attributes: {}, children: [], content: '?' },
       { name: 'AccNo', attributes: {}, children: [], content: '?' },
     { name: 'SCS', attributes: {}, children: [], content: '?' }]

目标对象将基于 name 属性和 content 属性:

The target object would be based on the name property and the content property:

   {'CarNo': '?', 'AccNo': '?', 'SCS': '?' }

我以为我可以减少这个,但我失败了:

I was thinking I could just reduce this but I am failing:

        const filteredResponseObj = Object.keys(rawResponseBodyObj).reduce((p,c)=>{
          if( c === 'name' ){
            p[c]=rawResponseBodyObj[c].content;
          }
          return p;
        },{});

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

What am I missing? clearly I have some issues with the reduction...

推荐答案

您的想法是正确的,但方法如下:

You had the right idea, but here is how to do it:

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

使用将对象数组转换为哈希映射,以对象的属性值作为索引

这篇关于将对象数组减少到 JS 中的 hashmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆