3

I have two objects of person:

var p1 = {firstName:"John", lastName:"Doe", age:46};
var p2 = {firstName:"Joanne", lastName:"Doe", age:43};

How can i add these objects to a persons array and access it by index?

All i know is to initialized the persons:

var persons = [
    {firstName:"John", lastName:"Doe", age:46},
    {firstName:"Joanne", lastName:"Doe", age:43}
];
1
  • var persons = [p1, p2] Commented Sep 5, 2016 at 9:27

5 Answers 5

7

To create an array of persons:

var persons = []; // initialize the array

persons.push({firstName:"John", lastName:"Doe", age:46}); // Add an object

persons.push({firstName:"Joanne", lastName:"Doe", age:43}); // Add another object

To retrieve the value at a specific index:

persons[1].firstName // "Joanne"
persons[1].lastName  // "Doe"
persons[1].age       // 43

To iterate through the array use a for loop, or any kind of loop:

for (var i = 0; i < persons.length; i++) {
    console.log( persons[i].firstName ); // writes first names to console
}
Sign up to request clarification or add additional context in comments.

Comments

1

To create an array literal use [] instead of {}.

9 Comments

@ShiftN'Tab — Which is the right syntax to create an object. Then you tried to put the objects in an array and you used the wrong syntax to create the array.
@ShiftN'Tab — You seem to have edited the question to fix the syntax. So now the code in the question works. The question doesn't appear to be asking anything now.
i do not ask for the initialization sir i asked for the insert of an array object
@ShiftN'Tab — Your code is creating an array and inserting two objects into it. I still don't understand what the problem is.
|
1

You can add each object by using the push method.
Cycle through your array and for each one persons.push(object).

Comments

1

An alternate approach to iterate through an array of these people is:

const people = persons.map((person, i) => {
  console.log(persons[i].firstName)
});

Comments

-1

You can use push method It will add the object to the end of the array.

see example:

<script>
var per1 ={firstName:"John", lastName:"Doe", age:46};
var per2 ={firstName:"Johny", lastName:"Doe", age:50};
var persons = [per1,per2];

var per3 ={firstName:"Johnonon", lastName:"Doe", age:52};
persons.push(per3);

</script>

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.