我想从json响应中获取最新的timeStamp和用户ID,将其实际的DataArray.status ==“ Approved”填充到模板上
{
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "@23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "@1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "@1233e",
"articles": ""
},
],
},
预期输出应为与该时间戳相对应的最新timeStamp和userId。 请帮助我。
答案 0 :(得分:1)
通过此操作,您可以获得具有批准状态的最新对象。
const data = {
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "@23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "@1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "@1233e",
"articles": ""
},
],
}
]
}
let dataArr = data.dataArray
dataArr.forEach((dataPoint, i) => {
let actualDataArray = dataPoint.actualDataArray
let sortedActualDataArray = actualDataArray.sort((a, b) => {
(new Date(a.timeStamp) > new Date(b.timeStamp)) ? 1 : -1
})
let timeStampElem = undefined
if(dataPoint.status != "Ok"){
timeStampElem = tempSearchArr[0]
}
else {
timeStampElem = tempSearchArr[1]
}
console.log(timeStampElem)
console.log(`TimeStamp: ${timeStampElem.timeStamp}`)
console.log(`UserID: ${timeStampElem.userID}`)
})
答案 1 :(得分:0)
尝试以下代码:
var jsonObj = {
"dataArray": [
{
"Id": 11,
"Name": "HJ Enterprises",
"Code": "HJC",
"description": "HJ APProved",
"Status": "OK",
"actualDataArray": [
{
"timeStamp": "2019-05-07-06.26.23.991068",
"status": "Approved",
"userID": "@23444",
"articles": ""
},
{
"timeStamp": "2019-05-07-06.37.27.978668",
"status": "Rejected",
"userID": "@1234",
"articles": "articles"
},
{
"timeStamp": "2019-05-08-06.26.28.991068",
"status": "Approved",
"userID": "@1233e",
"articles": ""
},
],
}
]
};
var approvedUsers = {};
var totalData = jsonObj.dataArray.length;
var i = 0;
while(i < totalData) {
var actualsData = jsonObj.dataArray[i].actualDataArray;
var actualLength = actualsData.length;
var j = 0;
while(j < actualLength) {
if (actualsData[j].status === "Approved") {
approvedUsers[actualsData[j].userID] = actualsData[j];
}
j += 1;
}
i += 1;
}
console.log(approvedUsers);
在此,我将在单独的var
中汇总状态为“已批准”的数据,最后在console.log()
中显示该数据。您可以根据需要使用此var
。