我有超过 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/