简体   繁体   中英

Define JavaScript object literal so that the properties exists for all objects in an array?

I define a JavaScript object literal with defaults so that my template can access them later:

self.emails = [{
    address: "",
    validation: {
        warning: false,
        message: "",
    }
}];

This works for self.emails[0] but I also need the properties to exist for self.emails[1] to self.emails[4] . Is there a better way to accomplish this than to type:

self.emails = [{
    address: "",
    validation: {
        warning: false,
        message: "",
    }
},
    address: "",
    validation: {
        warning: false,
        message: "",
    }
},
    address: "",
    validation: {
        warning: false,
        message: "",
    }
},
    address: "",
    validation: {
        warning: false,
        message: "",
    }
},
    address: "",
    validation: {
        warning: false,
        message: "",
    }
}];

Use a simple for loop:

self.emails = []
for (let i = 0; i < 5; i++) {
  self.emails.push({
    address: "",
    validation: {
      warning: false,
      message: "",
    }
  })
}

I would do this job as follows;

 var selfEmails = [{ address: "", validation: { warning: false, message: "", } }], longSelfEmails = Array(...Array(5)).map(o => { o = Object.assign({},(selfEmails[0])); o.validation = Object.assign({},o.validation); return o; }), modified = longSelfEmails.map((o,i) => {o.validation.message = i; o.address = "addr_0"+i; return o; }); console.log(modified); 

Now they are all an individual object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM