我有以下包含对象的示例对象,我想对其重新排序:
var thisarray = {
0 : { topic: "devices/one/humid/value", message: "1"},
1 : { topic: "devices/one/humid/unit", message: "%"},
2 : { topic: "devices/one/temp/value", message: "2"},
3 : { topic: "devices/one/temp/unit", message: "c"},
4 : { topic: "devices/two/humid/value", message: "1"},
5 : { topic: "devices/two/humid/unit", message: "%"},
6 : { topic: "devices/two/temp/value", message: "2"},
7 : { topic: "devices/two/temp/unit", message: "c"},
};
var arr = { };
for (var key in thisarray) {
// skip loop if the property is from prototype
if (!thisarray.hasOwnProperty(key)) continue;
var obj = thisarray[key];
var devicename = "";
var variablename = "";
var variableprop = "";
for (var prop in obj) {
// skip loop if the property is from prototype
if(!obj.hasOwnProperty(prop)) continue;
if(prop=="topic") {
var localstrings = obj[prop].split("/");
devicename = localstrings[1];
variablename = localstrings[2];
variableprop = localstrings[3];
} else if(prop=="message") {
//this line throws an error
arr[devicename][variablename][variableprop]=obj[prop];
}
}
}
console.log(arr);
这会引发错误
TypeError: Cannot read property 'humid' of undefined
我需要的结果:
arr = {
one : {
humid : { value: 1 , unit : '%'},
temp : { value: 2 , unit : 'c'}
},
two : {
humid : { value: 1 , unit : '%'},
temp : { value: 2 , unit : 'c'}
}
}
我尝试了很多方法,也一直在google上查找,但无法解决这个问题,欢迎任何指导
编辑:谢谢大家,Tai Le的解决方案非常完美,也感谢Marcelo Origoni也指出了我的错误,我在这里学到了很多东西,谢谢!
最佳答案
因为您没有初始化嵌套属性的值。这段代码可能不完全是你所期望的,但指出了你的问题是什么
var thisarray = {
0 : { topic: "devices/one/humid/value", message: "1"},
1 : { topic: "devices/one/humid/unit", message: "%"},
2 : { topic: "devices/one/temp/value", message: "2"},
3 : { topic: "devices/one/temp/unit", message: "c"},
4 : { topic: "devices/two/humid/value", message: "1"},
5 : { topic: "devices/two/humid/unit", message: "%"},
6 : { topic: "devices/two/temp/value", message: "2"},
7 : { topic: "devices/two/temp/unit", message: "c"},
};
var arr = { };
for (var key in thisarray) {
// skip loop if the property is from prototype
if (!thisarray.hasOwnProperty(key)) continue;
var obj = thisarray[key];
var devicename = "";
var variablename = "";
var variableprop = "";
for (var prop in obj) {
// skip loop if the property is from prototype
if(!obj.hasOwnProperty(prop)) continue;
if(prop=="topic") {
var localstrings = obj[prop].split("/");
devicename = localstrings[1];
variablename = localstrings[2];
variableprop = localstrings[3];
} else if(prop=="message") {
// Init value as empty object if it is undefined
arr[devicename] = arr[devicename] || {};
arr[devicename][variablename] = arr[devicename][variablename] || {};
arr[devicename][variablename][variableprop]=obj[prop];
}
}
}
console.log(arr);
关于javascript - 在javascript中将一个简单的java对象重新排序为3级对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852244/