Patrick Patrick - 6 months ago 11
Javascript Question

Add value into an array of Objects

I have this array of objects that i display on the UI table. It has 3 columns with name, contact and id.

[Object, Object, Object]
0:Object
name: "Rick"
Contact: "Yes"
id: 1
1:Object
name:"Anjie"
Contact:"No"
id: 2
2:Object
name:"dillan"
Contact:"Maybe"
id:3


Now, i add a new row to the top of table. So the newly added row into the array of objects, would look like this.

[Object, Object, Object,Object]
0:Object //newly added row. Since new row is added, it doesnt have any data.
name: ""
Contact: ""
id:
1:Object
name: "Rick"
Contact: "Yes"
id: 1
2:Object
name:"Anjie"
Contact:"No"
id: 2
3:Object
name:"dillan"
Contact:"Maybe"
id:3


I want the array of objects to look like this instead of above one.

[Object, Object, Object,Object]
0:Object //newly added row. Since new row is added, it doesnt have any data.
name: ""
Contact: ""
id: 4
1:Object
name: "Rick"
Contact: "Yes"
id: 1
2:Object
name:"Anjie"
Contact:"No"
id: 2
3:Object
name:"dillan"
Contact:"Maybe"
id:3


The only change is id value at 0th object. You can see i entered it as 4. It will check the max value in array of objects for id. In this case, it is 3. So it will increment by 1 and put it as the id value for newly added row.

Can someone let me know how to achieve this please.

Also, I had one more query.

If my id values are as follows.

1
2
3
4
5
6


And i delete 4 and 5. So new rows will be

1
2
5
6


Here, it will check max length as 4 and add id value of 5 to newly row. it will look somewhat like this.

5
1
2
5
6


In this case, 5 is repeated. I dont want this. I instead would like to see which is the highest value given to id, and then increment the id according to it. So it should look like this.

7
1
2
5
6

Answer

If you only care about the ID being unique, you can add the timestamp as the ID

Lets assume that your array is called peopleContact your code to add the item in the array of objects would look something like the following.

var person= new Object();
person.name= "";
person.Contact= "";
person.id = Date.now();

peopleContact.push(person);