hh54188
hh54188

Reputation: 15626

Confuse about array and object in node.js

I have a array for store object, which have an object in it already:

var obj = [{
    name: 'json',
    lang: 'en'
}];

console,.log(obj) //the result is OK;

then I want push another object into it, just like:

var newObj = {
    name: 'lee',
    lang: 'zh'
}

obj.push(newObj)

but after this I print the obj array,console.log(obj), the result is 2 !!

Why this happen? How can I solve this problem?To store object in array correctly

Upvotes: 0

Views: 5052

Answers (1)

xdazz
xdazz

Reputation: 160833

Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).

Upvotes: 5

Related Questions