【问题标题】:how to convert part of json response to map如何将部分json响应转换为地图
【发布时间】:2015-05-08 14:07:30
【问题描述】:

我的 JSON 响应看起来像这样

{"values": 
 [
        {
            "type": "NAME",
            "match": "EXACT",
            more properties here
        },
        {
            "type": "LASTNAME",
            "match": "AMBIG",
            more properties here
        }
] }

如何将其转换为仅包含类型和匹配属性的 javascript 映射?

例如

{
 'NAME' : 'EXACT' ,
 'LASTNAME' : 'AMBIG' 
}

【问题讨论】:

    标签: javascript jquery json node.js


    【解决方案1】:

    这是我的尝试:http://jsfiddle.net/u9ycpLgs/

    遍历 test.values 并创建一个新对象,其中类型的值是新键,匹配的值是新值。

    var test = {
        "values": [{
            "type": "NAME",
                "match": "EXACT"
        }, {
            "type": "LASTNAME",
                "match": "AMBIG"
        }]
    };
    
    keyValuePairs = {};
    
    test.values.forEach(function (item) {
        keyValuePairs[item.type] = item.match;
    });
    
    
    console.log(JSON.stringify(keyValuePairs));
    
    /*
     Output:
    
      {"NAME":"EXACT","LASTNAME":"AMBIG"}
    */
    

    【讨论】:

    • 您可以使用reduce 将您的答案转换为单行字。 hashMap = test.values.reduce(function(accumulator, item) { return accumulator[item.type] = item.match; }, {})
    • @Pete,好电话。将其发布为答案,我会投票给它!
    猜你喜欢
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2018-04-21
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多