我有以下包含对象的示例对象,我想重新排序:
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'}
}
}
我一直在尝试很多方法,而且我一直在寻找谷歌,但无法解决这个问题,欢迎任何指导
编辑:谢谢大家,泰乐的解决方案非常完美,也感谢Marcelo Origoni指出我的错误,我在这里学到了很多,谢谢!答案 0 :(得分:1)
错误很明显,arr[devicename]
未定义,您应该这样做:
arr[devicename] = {};
arr[devicename][variablename] = {};
arr[devicename][variablename][variableprop]=obj[prop];
那个,你将devicename
和variablename
定义为空对象,你可以创建和修改它的属性
答案 1 :(得分:1)
因为你没有为nest属性初始化值。此代码可能不完全符合您的预期,但指出您的问题是什么
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);