1

I have a javascript object which I use as type of map with key value pairs.

Population of this map occurs when value is injected to it from controller :

var people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim"}

I want to create a new object but with one more entry i.e in pseudo code

var new_people = people + {11: "John"}

I tried to copy people to new people first and then :

new_people.\"11\" = "John"

and

new_people."11" = "John"

Both produce failure. While any string instead of number works i.e

new_people.anystring = "John"

var new_people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim", "anystring":"John"}
3

4 Answers 4

6

You could use indexing:

new_people['11'] = 'John';
Sign up to request clarification or add additional context in comments.

Comments

2

You just need to add a key value to the object:

people['11'] = "John";

If the key was a valid identifier name(not a number) you could have used this:

people.key = "John";

You have to use the indexes when it's not a valid variable name:

people["~!#$#$#HV"] ="some value";

Comments

2

You will have a problem because variables hold references when storing objects. By mutating new_people, you are also mutating people.

var people = {"1":"James"}
console.log(people);       // Object {1: "James"}
var new_people = people;
new_people["2"] = "Jimmy";
console.log(people);       // Object {1: "James", 2: "Jimmy"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

You'll need to clone the object first then mutate the clone so you don't affect the original object.

One easy way to do that is using the underscore.js extend() method like this:

var new_people = _.extend({}, people, {"2": "Jimmy"});
console.log(people);       // Object {1: "James"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

Or similarly, with jQuery extend() like this:

var new_people = $.extend({}, people, {"2": "Jimmy"});
console.log(people);       // Object {1: "James"}
console.log(new_people);   // Object {1: "James", 2: "Jimmy"}

3 Comments

Yup: the line var new_people = people + {11: "John"} in the question doesn't create a new object. (It actually creates a string.)
@PaulD.Waite the OP indicated that var new_people = people + {11: "John"} was pseudo code.
@JeffShaver: ah, yes I see. Hadn't noticed that.
0

@Gandalf StormCrow Here is a code: jsfiddle

var people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim"};

var newpeople = {"11": "John"};
jQuery.extend(people, newpeople);
//Now: people = {"2":"Brad","3":"Antonio","5":"Stacy","6":"Marry","1":"Jim","11": "John"}

for(var i in people){
  alert(people[i]);  
};

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.