使用Javascript将JSON对象属性提取到新数组中

时间:2017-07-30 09:53:54

标签: javascript arrays json

我有100多种JSON对象,格式为:

{
"grants":[
{
    "grant":0,
    "ID": "EP/E027261/1",
    "Title": "Semiconductor Research at the Materials-Device Interface",
    "PIID": "6674",
    "Scheme": "Platform Grants",
    "StartDate": "01/05/2007",
    "EndDate": "31/10/2012",
    "Value": "800579"
}, ... more grants

我希望能够将EndDate和Value抓取到一个新数组中。像下面的输出一样。

"extractedGrants":[
{
    "EndDate": "31/10/2012",
    "Value": "800579"
}, ... more extracted objects with EndDate and Value properties.

我认为正确的方法是使用array.map(function(a){});但是我无法在函数内部获得代码。

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用对象的销毁和结果数组的新对象。



var object = { grants: [{ grant: 0, ID: "EP/E027261/1", Title: "Semiconductor Research at the Materials-Device Interface", PIID: "6674", Scheme: "Platform Grants", StartDate: "01/05/2007", EndDate: "31/10/2012", Value: "800579" }] },
    result = object.grants.map(({ EndDate, Value }) => ({ EndDate, Value }));

console.log(result);




ES5



var object = { grants: [{ grant: 0, ID: "EP/E027261/1", Title: "Semiconductor Research at the Materials-Device Interface", PIID: "6674", Scheme: "Platform Grants", StartDate: "01/05/2007", EndDate: "31/10/2012", Value: "800579" }] },
    result = object.grants.map(function (a) {
        return { EndDate: a.EndDate, Value: a.Value };
    });

console.log(result);