如何将json响应的一部分转换为map

how to convert part of json response to map

本文关键字:一部分 转换 map 响应 json      更新时间:2023-09-26

我有一个JSON响应,看起来像这个

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

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

例如

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

以下是我的尝试: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"}
*/