0

I have a basic question that I'm not sure how to search on a solution as I'm not exactly sure what term to search on. Sorry if this is 101 stuff.

I have a javascript object I'm trying to add values to, and not sure how. If I have the following, how to I add a record?

var context = {
    people: [
        {firstName: 'Homer', lastName: 'Simpson'},
        {firstName: 'Peter', lastName: 'Griffin'},
        {firstName: 'Eric', lastName: 'Cartman'},
        {firstName: 'Kenny', lastName: 'McCormick'},
        {firstName: 'Bart', lastName: 'Simpson'}
    ]
};

How do I add another value to "people"

1 Answer 1

2

Simply use the array.push method:

context.people.push({
    firstName: 'Example',
    lastName: 'Person'
});

That will put it in the last slot of the array (expanded to fit the new element, of course).

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

2 Comments

Thank you! Can you recommend what term I should have searched on?
@SteveV what do you mean? What you should have searched for to find array.prototype.push?

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.