如何在for循环中创建对象时在另一个JavaScript对象中添加JavaScript对象?

时间:2017-05-09 17:08:12

标签: javascript

我看了其他StackOverflow的类似问题。但这些与我正在寻找的完全不同。

var schemaField = {},
                validation = {};
            for (var i = 0; i < gridConfig.Schemas.length; i++) {
                var schema = gridConfig.Schemas[i];
                schemaField[schema.FieldName] = {
                    type: schema.FieldType,
                    editable: schema.FieldEditable,
                    //Below block is wrong, but this is what I am trying to achieve
                    validation = {
                        required: schema.FieldRequired
                    }                        
                }
            }

我需要在主对象 schemaField [schema.FieldName] 下添加该验证对象。请帮忙!!!

2 个答案:

答案 0 :(得分:0)

你需要这样做:

key: value

对象只是JavaScript中的地图(字典)。您可以继续使用对象文字符号:value其中.blockE{ height: 15vw; background-color: red; position: relative; top: 308px; margin-top: 1%; width: 59%; margin-left: 1%; 可以是任何内容,包括另一个对象文字。

答案 1 :(得分:0)

var schemaField = {},
validation = {};
for (var i = 0; i < gridConfig.Schemas.length; i++) {
     var schema = gridConfig.Schemas[i];
     schemaField[schema.FieldName] = {
        type: schema.FieldType,
        editable: schema.FieldEditable,
        //Don't assign using = but :
        validation: {
           required: schema.FieldRequired
        } 
     }
     //Or if you want to assign outside
     //schemaField[schema.FieldName].validation = {
     //  required: schema.FieldRequired
     //}                      
  }