用来自另一个对象JavaScript的部分数据填充空对象

时间:2018-11-19 08:13:50

标签: javascript object nested

我有一个这样表示的空对象:

myObj = {
 myObjName = null;
 myObjType = null;
 myObjOcc = null;
}

还有一个对象,其对象表示如下:

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""
              },
       }
}

我必须将数据从 mainObj 中的对象插入到 myObj

映射应该是这样的:

myObjName = attName
myObjType = attType
myObjOcc = attOccurance

要考虑的另一件事是mainObj中的 id ,因为 Ob2 必须嵌套在 Ob1 Ob3 < / strong>必须嵌套在 Ob2

所以myObj应该看起来像这样:

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""
            }
        }
   }
}

代码中有这部分,它确定每个对象属于哪个级别:

for each(var oneObj in mainObj){
    .
    .
    switch (true) {
                 case  oneObj.id < 100: levelId=1; break;
                 case  oneObj.id < 10000: levelId=2; break;
                 case  oneObj.id < 1000000: levelId=3; break;
    }
    .
    .
}

如果有人可以帮助我,我该怎么做?

1 个答案:

答案 0 :(得分:0)

您要说的是对象看起来很像JSON。但是,这就是您要完成想要说的结果的方式。

// var myObj = {};
// for (key in mainObj) {
//   const name = mainObj[key].name
//   myObj[name] = {
//     myObjName: mainObj[key].properties.attName,
//     myObjType: mainObj[key].properties.attType,
//     myObjOcc: mainObj[key].properties.attOccurance
//   }
// }

// console.log(myObj)

var 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"'
        },
    }
}

var myObj = {};
for (key in mainObj) {
  const name = mainObj[key].name
  myObj[name] = {
    myObjName: mainObj[key].properties.attName,
    myObjType: mainObj[key].properties.attType,
    myObjOcc: mainObj[key].properties.attOccurance
  }
}

console.log(myObj)