简体   繁体   中英

define property array of objects in Javascript

I have initialized an object that I wish to add to dynamically. Specifically I want to add array of objects to this object. I have tried the below but neither work.. is there a way to do this correctly? The final output should be object1.property1[0].value = 42 and object1.property1[0].writable = false .

const object1 = {};

Object.defineProperty(object1, 'property1', '' );
object1.property1 = [{value: 42, writable: false}];


const object1 = {};
Object.defineProperty(object1, 'property1', [{value: 42, writable: false}] );

Try using value property from descriptor argument:

 const object1 = {}; Object.defineProperty(object1, 'property1', { value: [{ value: 42, writable: false }] }); console.log(object1.property1[0].value); console.log(object1.property1[0].writable);

The object descriptor must be declared as follow:

{value: [{value: 42}], writable: false}

 const object1 = {}; Object.defineProperty(object1, 'property1', {value: [{value: 42}], writable: false}); console.log(object1.property1[0].value)

Since you specified you wanted to add an array of objects to the object, this solution is similar to other answers, but should demonstrate adding an array with more than one element:

 const obj = {}; Object.defineProperty(obj, 'property', { value: [{ value: 42, writable: false }, { value: 55, writable: false } ] }); console.log(obj.property[0].value); console.log(obj.property[0].writable); console.log(obj.property[1].value); console.log(obj.property[1].writable);

Of course, your writable isn't going to do anything, since it'll be treated as just another property. Due to the fact that your property is an array of objects (eg, [{...},{...}] ), what you may want to do is iterate over that array and freeze those objects:

obj.property.forEach(o=>Object.freeze(o))
obj.property[0].value=33;  // when frozen you won't be able to update the value

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