0

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.

2
  • 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. Commented Mar 12, 2019 at 17:38
  • 3
    Possible duplicate of Declaring array of objects Commented Mar 12, 2019 at 17:39

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

0

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

var arrOfObjects = new Array(10).fill({
  field1: 'value1',
  field2: 'value2'
})

Comments

0

try this:

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

or

var array = 
[
 {
  field1: "value1", 
  field1: "value2" 
 }
];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.