3

I am trying to learn JS. It seems simple but I am not sure how to do this.

having this javascript object based on this good thread

var people = {
  1: { name: 'Joe' },
  2: { name: 'Sam' },
  3: { name: 'Eve' }
};

How do I add the following value

4: { name: 'John' }

To get name Eve I write

 people["1"].name
2
  • This is the JSON notation: json.org Commented May 27, 2009 at 20:44
  • In the original thread, the keys were sparse (1, 3, 8) not consecutive (1,2,3), so I don't know if all the suggestions to switch to an array fit what the questioner wants to do. Commented May 27, 2009 at 20:47

2 Answers 2

15

Assign the anonymous object to it the way you would any other value.

people["4"] = { name: 'John' };

For what it's worth, since your keys are numeric you could also use zero-based indices and make people an array.

var people = [ { name: 'Joe' },
               { name: 'Sam' },
               { name: 'Eve' } ];

and

alert( people[2].name ); // outputs Eve
people[3] = { name: 'John' };
Sign up to request clarification or add additional context in comments.

Comments

1

I think people should be an array :

var people = [
  { name: 'Joe' },
  { name: 'Sam' },
  { name: 'Eve' }
];

as the keys are integers, so you can add a person by :

people.push({name:'John'});

You can acces to the people by doing :

var somebody = people[1]; /// >>> Sam

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.