Yash Suryavanshi
Yash Suryavanshi

Reputation: 67

Add an object at the beginning of array

I know it's easy, but I can't quite get it.

function submitNewComment() {
   var noo = 0; //array index
   var userName = document.getElementById('user-name').value; //textbox
   var commentBox = document.getElementById('main-comment').value; //textbox
   var now = new Date();
   mili = now.getTime(); //time in milisecond
   var element = [];
   element.push({
      "no": noo, //array index
      "username": userName,
      "date": mili,
      "body": commentBox,
      "likes": "0",
      "parent": null
   });
console.log(element);
noo++;
console.log(noo);
}

In short, I need to add create a variable as an array containing objects. When I run the function, it doesn't quite work as I hoped. I am missing something.

The problem exists when you run the function for the second time. Ideally 2nd object should be created but the first one gets updated. So, at the end of 2nd run and every other run there after, length of the array remains 1.

Upvotes: 0

Views: 426

Answers (3)

misterhtmlcss
misterhtmlcss

Reputation: 391

You have a few issues. One you need to have a way to get the data after the page loads.

  1. You need a button or some other method of action.
  2. You confusing yourself with your object creation. If it's a factory function for creating objects then 'this.[label]' is valid, but if you are just pushing form data as an object into an array then do as I've suggested below. Does what I did make sense?
  3. Also I didn't change it here, but the best way to create a date in milliseconds is Date.now(). Use this method going forward, it'll both shorten and simplify your code.
  4. Any questions?

var element = []; 
var btn = document.getElementById('btn');
btn.addEventListener('click', submitNewComment);
      
function submitNewComment() {
 var userName = document.getElementById('user-name').value
 var commentBox = document.getElementById('main-comment').value
 var now = new Date();
 var milliseconds = now.getTime();
  element.unshift({
    no: "test",
    username: userName,
    date: milliseconds,
    body: commentBox,
    likes: 0,
    parent: null,
  });
console.log(element);
}
 <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>misterhtmlcss</title>
  </head>
  <body>
		<input type="text" name="user-name" id="user-name">
    <input type="text" name="main-comment" id="main-comment">
    <button id="btn">Submit</button>
    <script src="index.js"></script>
  </body>
</html>

Update. I realized I left this declaration inside the function meaning it wouldn't retain continuous submissions which you may have wanted based on what you did say.

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89314

You can use Array.prototype.unshift() to add elements to the start of an Array. This method returns the new length of the Array.

var element = [];
element.push({
      "no": "noo", //temp variable
      "username": "userName",
      "date": "mili",
      "body": "commentBox",
      "likes": "0",
      "parent": null
});
element.push({"something": "else"});
var newLen = element.unshift({"object": "one"});
console.log(element);
console.log("New length of Element Array: "+newLen);

Upvotes: 0

Simranjit Singh
Simranjit Singh

Reputation: 404

Use .unshift( object ) to prepend to an array.

let a = [1,2,3,4];
console.log( a );
a.unshift(5);
console.log( a );

Upvotes: 0

Related Questions