0
var object = {

}

socket.on('call', function(data){
  console.log(data); // On console: { number: 68, name: 'John' }
  object.push(data);
});

In the console.log I get the object just fine. But the push function doesn't seem to be working.

    object.push(data);
            ^
 
TypeError: object.push is not a function
3
  • 1
    push can be used for array not for object Commented Sep 21, 2017 at 16:48
  • 1
    push is a member function of Array, not Object. You can't "push" anything into an object. Try var arr = []; ... arr.push(data);; Commented Sep 21, 2017 at 16:48
  • Sorry, stackoverflow.com/a/7261466/8241267 this answer really tripped me. Commented Sep 21, 2017 at 16:50

2 Answers 2

0

object here is an Object, so not have the push function.

If you want to use an object use object[key] = value; or object.key = value;


Array.push in others hand exists.

var object = [];

object.push(value);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, but is it a good idea to have an array with a bunch of objects inside it?
@TwitchClips, in JS you can push objects inside an array. It is not a bad practice.
0

You can't use push() function for Objects. Actually there is no function named push() for Objects. You need to use an Array if you want to use push.

Hope this code helps.

  var myArray = ['A','B'];
  myArray.push('C');
  console.log(myArray);
  //["A", "B", "C"]

  var myObject = {foo:"bar"};
  myObject.name = "John";
  console.log(myObject);
  //{foo: "bar", name: "John"}

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.