我在想我对javascript
了解多少,但我必须承认我什么都不知道。
我一直在尝试创建一个自定义对象,但似乎仍然没有。
var currentline=[
{"NAME":"Battery For Alarm Panel","CODE":"POWER MAX","OWN":"ONM"},
{"NAME":"Fire Alarm Panel","CODE":"SANA SERVICES","OWN":"ONM"}...
]
通过following question的帮助,我可以创建以下对象
// skipping main loop code for brevity
detailObj=[];
loop{
singleObj = {};
singleObj[currentline['NAME']] = {};
singleObj[currentline['NAME']][currentline['CODE']] = {};
singleObj[currentline['NAME']][currentline['CODE']][currentline['OWN']] = value;
detailObj.push(singleObj);
}
并获得以下detailObj
[
{"Battery For Alarm Panel":{"POWER MAX":{"ONM":7}}},
{"Fire Alarm Panel":{"SANA SERVICES":{"ONM":8}}}
]
我怎样才能push
一个对象变成对象,尽管进入数组并且可以获得跟随对象?
{
"Battery For Alarm Panel":{"POWER MAX":{"ONM":7}},
"Fire Alarm Panel":{"SANA SERVICES":{"ONM":8}}
}
是否有任何在对象中添加对象的功能?
答案 0 :(得分:1)
如果currentline
是这样的
var currentline = [{
"NAME": "Battery For Alarm Panel",
"CODE": "POWER MAX",
"OWN": "ONM",
"VALUE": 7
}, {
"NAME": "Fire Alarm Panel",
"CODE": "SANA SERVICES",
"OWN": "ONM",
"VALUE": 8
}];
只需更改detailObj
一个对象而不是推送,将NAMES
值指定为键,就像这样
var detailObj = {}; // An object, not an array
currentline.forEach(function(line) {
detailObj[line.NAME] = {};
detailObj[line.NAME][line.CODE] = {};
detailObj[line.NAME][line.CODE][line.OWN] = line.VALUE;
});
console.log(detailObj);
# { 'Battery For Alarm Panel': { 'POWER MAX': { ONM: 7 } },
# 'Fire Alarm Panel': { 'SANA SERVICES': { ONM: 8 } } }