我有一个像这样的JSON对象
var response = [{"2017-04-19T18:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"}},{"2017-04-20T15:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"15:00:12"}}]
我想把它转换成这样的东西
[{"2017-04-19":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"}},{"2017-04-20":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"15:00:12"}}]
我试过这个
for(var key in response){
if(response.hasOwnProperty(key)){
key = key.substring(0,10);
}
}
但这不起作用。我哪里错了?
快速修改: 目前的答案似乎有效,但有些对象具有相同的日期但时间不同。因此,输出仅显示特定时间的数据。有什么办法可以解决这个问题。例如:
var response = [{"2017-04-19T18:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"}},{"2017-04-19T15:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"15:00:12"}}]
我希望将此输出为类似
的内容[{"2017-04-19":[{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"},{"2017-04-19T15:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"15:00:12"}]}]
答案 0 :(得分:1)
在您的情况下,问题是您指的是response
,它是一个对象数组。但是你需要response[0]
从第0个索引获取元素
var response = [{
"2017-04-19T18:00:12+05:30": {
"command": "00",
"device_id": "THB1",
"voltage": "229",
"e1": "00.00",
"date_time": "18:00:12"
}
}]
for (var key in response[0]) {
if (response[0].hasOwnProperty(key)) {
// creating substring from key name
var x = key.substring(0, 10);
// in same object creating a new key & value using the
// substring and previous value
response[0][x] = response[0][key]
// deleting the old key
delete response[0][key];
}
}
console.log(response)

答案 1 :(得分:1)
试试这个,这应该可以解决你的问题
var response = [{"2017-04-19T18:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"}},{"2017-04-19T17:00:16+05:30":{"command":"008550","device_id": "THUGHGB1", "voltage": "229", "e1": "00.00", "date_time":"18:00:12"}},{"2017-04-20T15:00:12+05:30":{"command":"00","device_id": "THB1", "voltage": "229", "e1": "00.00", "date_time":"15:00:12"}}]
var newResponse = [];
for (var i = 0; i < response.length; i++) {
for (var key in response[i]) {
var newKey = key.substring(0, 10);
var newObj = {};
if (newResponse.length) {
for (var j = 0; j < newResponse.length; j++) {
for (var newIdx in newResponse[j]) {
if (newIdx === newKey) {
newObj[key] = response[i][key];
} else {
newObj[newKey] = response[key]
}
}
}
} else {
newObj[newKey] = response[key]
}
newResponse.push(newObj)
}
}
response = newResponse;