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

标签 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) {});但我无法在函数内部获取代码。

谢谢。

最佳答案

您可以使用对象的破坏和结果数组的新对象。

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);

关于javascript - 使用 Javascript 将 JSON 对象属性提取到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398545/

相关文章:

javascript - 在步骤中更改检查文件大小和文件类型 Jquery-Steps

带有 Angular ng-repeat 的 JavaScript array.push(对象)未按预期运行

c - C 中的数组变异

java - 我不断收到编译器错误,说 Rainfallmain.java :13: error: <identifier> expected.

javascript - 使用 javascript 通过 DOMContentLoaded 提供较小的图像

javascript - 如何在 OpenLayers 3 中通过 map 边缘绘制测地线?

javascript - 为什么Jquery ajax要给String添加斜杠?

javascript - localStorage.removeItem 基于值

c - 使用 C 代码难以读取 DNA 序列文件

javascript - 从 wunderground API 访问 json 数据?