简体   繁体   English

如何从JSON对象中创建两个具有不同值的数组?

[英]How to create two arrays with different values in them from a JSON object?

I have the following JSON data: 我有以下JSON数据:

jobHistoryJsonLst = [{
  "uuid" : "bGd_AAABNaMAAAFQHvY0UyTa",
  "startDate" : "2015-10-01 15:22:21",
  "endDate" : "2015-10-01 15:22:24",
  "executionTime" : "0:0:2.951"
}, {
  "uuid" : "lat_AAABqh4AAAFPQ8k0U_qu",
  "startDate" : "2015-09-23 10:50:02",
  "endDate" : "2015-09-23 10:50:06",
  "executionTime" : "0:0:3.284"
}]

I would like to create two different arrays from the above JSON object. 我想从上面的JSON对象创建两个不同的数组。 One should contain all the startDate data and the other should contains all the executionTime data. 一个应包含所有startDate数据,另一个应包含所有executeTime数据。

Expected Output: 预期产量:

startDateArr = ['2015-10-01 15:22:21', '2015-09-23 10:50:02']
execTimeArr = ['0:0:2.951', '0:0:3.284']

You can use .map or simple loop, like this 您可以使用.map或简单循环,像这样

 var jobHistoryJsonLst = [{ "uuid" : "bGd_AAABNaMAAAFQHvY0UyTa", "startDate" : "2015-10-01 15:22:21", "endDate" : "2015-10-01 15:22:24", "executionTime" : "0:0:2.951" }, { "uuid" : "lat_AAABqh4AAAFPQ8k0U_qu", "startDate" : "2015-09-23 10:50:02", "endDate" : "2015-09-23 10:50:06", "executionTime" : "0:0:3.284" }]; var dates = [], times = [], len = jobHistoryJsonLst.length, i; for (i = 0; i < len; i++) { dates.push(jobHistoryJsonLst[i].endDate); times.push(jobHistoryJsonLst[i].executionTime); } console.log(dates, times); // or with .map var dates = jobHistoryJsonLst.map(function (el) { return el.endDate; }); var times = jobHistoryJsonLst.map(function (el) { return el.executionTime; }) console.log(dates, times); 

You can either use map() which means processing it twice or one loop with forEach and push it to the array yourself. 您可以使用map(),这意味着对其进行两次处理,也可以使用forEach进行一次循环,然后将其自己推送到数组中。

jobHistoryJsonLst = [{
  "uuid" : "bGd_AAABNaMAAAFQHvY0UyTa",
  "startDate" : "2015-10-01 15:22:21",
  "endDate" : "2015-10-01 15:22:24",
  "executionTime" : "0:0:2.951"
}, {
  "uuid" : "lat_AAABqh4AAAFPQ8k0U_qu",
  "startDate" : "2015-09-23 10:50:02",
  "endDate" : "2015-09-23 10:50:06",
  "executionTime" : "0:0:3.284"
}];

var start = jobHistoryJsonLst.map( function (obj) { return obj.startDate; } );
var end = jobHistoryJsonLst.map( function (obj) { return obj.endDate; } );

//or

var start = [], 
end = [];
jobHistoryJsonLst.forEach( function(obj) { 
    start.push(obj.startDate); 
    end.push(obj.endDate); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM