映射Json以形成一个数组

时间:2017-05-08 20:04:23

标签: javascript ecmascript-6

以下是我的Json

"Issues": [
    {
        "Id": null,
        "Key": "Project20",
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Rya"
            },
            {
                "Key": "UserName",
                "Value": "RH"
            },
            {
                "Key": "Count",
                "Value": "350"
            }
        ]
    },
    {
        "Id": null,
        "Key": "Project30",
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Mike"
            },
            {
                "Key": "UserName",
                "Value": "ML"
            },
            {
                "Key": "Count",
                "Value": "90"
            }
        ]
    }
]

我需要映射这个Json以形成下面的数组

{ "Display Name": 'Rya', "UserName" : "RH", value: 350, url: "Project20" },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90, url:"Project30" }

基本上,我需要在我的数组中获取Key。

我试过

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc), {}));

这给了我

{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }

但我还需要数组中的Key字段

1 个答案:

答案 0 :(得分:4)

使用reduce的初始值参数。因此,而不是{}传递{ url: o.Key }

Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc),
                                { url: o.Key }));

对于IE上的用户,您需要使用与ES5兼容的语法:

Issues.map(function (o) {
    return o.Values.reduce(function (acc, pair) {
        acc[pair.Key] = pair.Value;
        return acc;
    }, { url: o.Key });
});

var Issues = [
    {
        "Id": null,
        "Key": "Project20",
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Rya"
            },
            {
                "Key": "UserName",
                "Value": "RH"
            },
            {
                "Key": "Count",
                "Value": "350"
            }
        ]
    },
    {
        "Id": null,
        "Key": "Project30",
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Mike"
            },
            {
                "Key": "UserName",
                "Value": "ML"
            },
            {
                "Key": "Count",
                "Value": "90"
            }
        ]
    }
];

var result = Issues.map(function (o) {
    return o.Values.reduce(function (acc, pair) {
        acc[pair.Key] = pair.Value;
        return acc;
    }, { url: o.Key });
});

console.log(result);