如果有人可以告诉我,我该如何从这个平面对象结构中进行操作:
mainObj = {
"Ob1": {
"id": 1,
"name": "Ob1",
"properties": {
"attName": "A1",
"attType": "string",
"attOccurance": "minOccurs="1""
},
},
"Ob2": {
"id": 101,
"name": "Ob2",
"properties": {
"attName": "B1",
"attType": "string",
"attOccurance": "minOccurs="1""
},
}
"Ob3": {
"id": 10001,
"name": "Ob3",
"properties": {
"attName": "C1",
"attType": "string",
"attOccurance": "minOccurs="1""
},
}
}
为此,它嵌套在另一个对象中,但带有平面对象的数据:
myObj = {
"Ob1": {
"myObjName": "A1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob2": {
"myObjName": "B1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob3": {
"myObjName": "C1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
}
}
}
}
嵌套逻辑是,如果下一个对象的ID大于上一个对象的ID,则它是其子对象。 这是逻辑:
for each(var obj in mainObj){
switch (true) {
case obj.id < 100: levelId=1; break;
case obj.id < 10000: levelId=2; break;
case obj.id < 1000000: levelId=3; break;
case obj.id < 100000000: levelId=4; break;
}
}
我只有这个,但是我不知道如何嵌套它们:
for (key in mainObj) {
myObj.myObjName = mainObj[key].properties.attName,
myObj.myObjTyp = mainObj[key].properties.attType,
myObj.myObjOcc = mainObj[key].properties.attOccurance
}
如果有人能告诉我该怎么做?
答案 0 :(得分:1)
给出输入和输出,这就是我想出的。看看是否有帮助。
尽管有很多情况,我认为我不确定输出应该是什么。
const mainObj = {"Ob1": { "id": 1, "name": "Ob1", "properties": { "attName": "A1", "attType": "string", "attOccurance": "minOccurs='1'" },},"Ob2": { "id": 101, "name": "Ob2", "properties": { "attName": "B1", "attType": "string", "attOccurance": "minOccurs='1'" }, }, "Ob3": { "id": 10001, "name": "Ob3", "properties": { "attName": "C1", "attType": "string", "attOccurance": "minOccurs='1'" }, }, "Ob4": { "id": 202, "name": "Ob4", "properties": { "attName": "D1", "attType": "string", "attOccurance": "minOccurs='1'" } }}
let levelKey = {}, newObj = {}
function getLevel(id) {
let level = 1
while(parseInt(id / 100) > 0) {
level++
id = id / 100
}
return level
}
function getLastLevel(id) {
id--
while(id > 0) {
if(levelKey[id]) return id
id--
}
return id
}
function getObj(str) {
return str.split('.').reduce((o, d) => o[d], newObj)
}
for( let [k, v] of Object.entries(mainObj)) {
let level = getLevel(v['id'])
let obj = {
myObjName: v.properties.attName,
myObjType: v.properties.attType,
myObjOcc: v.properties.attOccurance
}
let lastLevel = getLastLevel(level) || level
levelKey[lastLevel]
? (getObj(levelKey[lastLevel])[k] = obj, levelKey[level] = levelKey[lastLevel] + '.' + k)
: (newObj[k] = obj, levelKey[level] = k)
}
console.log(newObj)