简体   繁体   中英

push an assoc object into array

says I've this :

var user = [{'id':1,'gender':'male'},{'id':2,'gender':'female'}]

I want to use push() to insert

'owner':true

into the first array so that it become like this

var user = [{'id':1,'gender':'male','owner':true},{'id':2,'gender':'female'}]

I tried

user[0].push({'owner':true}); 

but it doesn't work tht way.

You are not pushing an object into an array, you are pushing an object into an object.
You can do this by using jquery's extend method.

var object = $.extend({}, object1, object2);

@Kim Gysen gave you a solution that works. I think you're getting the logic between Arrays and Objects confused I just wanted to give you a solution using only JavaScript that may help you understand just what's going on here. Using libraries like jQuery are a great way to save time but for you I think it would be helpful to have a more comprehensive understanding.

user[0]['owner'] = true;

In the code above you are accessing your array by the 0th index which in this case is "'id':1" and adding a new property to it using Bracket Notation. Another way to do this would be using Dot Notation:

user[0].owner = true;

Think about the process of adding a property to an object:

var myObj = {};
myObj['newKey'] = "I'm a new value";
myObj['newKey2'] = "I'm an even newer value!"; 

The reason I gave you an answer is it may seem convenient to use jQuery but understanding JavaScript principles and syntax will help you out in the long run. Some good resources for you I'd suggest are CodeSchool and CodeAcademy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM