-1

I am new to json and javascript but I have some experience with Java. I wanted to know how to create an array of objects but not sure how to design. What I want to do is to be able to call

object1.field1

where object1 is stored in an array like

array = [object1, object2, object3...];

and inside object1 would look like

object1:
   field1: value1,
   field2: value2,

So my question is how would I create the array to hold these values so I can use it for testing? I was thinking either two possible design:

array: [
  object1:{
    field1: value1, 
    field2: value2}, 
  object2: {
    field1: value1, 
    field2: value2}]

or

array: {
  object1:[
    field1: value1, 
    field2: value2], 
  object2: [
    field1: value1, 
    field2: value2]}

I was thinking the first one would be correct because it wouldn't be possible to call object1.field1 if the fields were stored in an array.

H. Manner
  • 195
  • 2
  • 9
  • 4
    your 2nd option is not valid JS. stick with the first, it's actual code, the 2nd is trying to use an array like it's an object. – Steven Stark Mar 12 '19 at 17:38
  • 3
    Possible duplicate of [Declaring array of objects](https://stackoverflow.com/questions/15742442/declaring-array-of-objects) – k3llydev Mar 12 '19 at 17:39

4 Answers4

0

try this:

var array = [];
var object = { field1:"value1", field2:"value2" };
array.push(object);

or

var array = 
[
 {
  field1: "value1", 
  field1: "value2" 
 }
];
Lugarini
  • 732
  • 5
  • 11
  • 29
0

Your first option is close to the actual code

You define your object by: var object = {};

And you can set or get its properties by using object.field1 = "value1"; or console.log( object.field1 );

Best of luck!

Sorin Buturugeanu
  • 1,682
  • 4
  • 18
  • 32
0

Your fist option is correct. You can create

let myArray = [
   {
       field1: value1, 
       field2: value2
   }, 
   {
       field1: value1, 
       field2: value2
   }
]

However, with a JS array you cannot do myArray.object1, cause this way only access object properties. To access object1 you need to get its index in the array, like myArray[0] gets the array first element, equivalent to object1

0

This is all you need (replace 10 with whatever length you need)

var arrOfObjects = new Array(10).fill({
  field1: 'value1',
  field2: 'value2'
})
iacobalin
  • 513
  • 2
  • 9