Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

How to add new value in first index array of objects in javascript

0 Kudos

var myobjs=[{

name:mohan,

age:28,

},

{name:ram,

age:28,

dept:csc},

{name:jhon,

age:28,

dept:mech}];

how can i insert dept in the first index of the object in java script

i want output like this

{name:mohan,

age:28,

dept:csc

},

{name:ram,

age:28,

dept:csc},

{name:jhon,

age:28,

dept:mech};

3 REPLIES 3

mateuszadamus
Active Contributor
0 Kudos

Hi,

Try using the unshift method like so: your_array.unshift( new_element_of_the_array );

regards,

Mateusz

venkateswaran_k
Active Contributor
0 Kudos

Hi

You can do something like this.

(you may correct the syntax)

var original = {
  name: "abc",
  age: "25"
};

var final = {
  name: "abc",
  value: "25"
  dept : "xxx"
};


for (let i = 0; i < original.length; i++) {
 
 final.name[i] = original.name[i]
 final.age[i] = original.age[i]
 if original.dept[i] is ''
 {  .....}
}


Regards,

Venkat

Grimmig
Advisor
Advisor
0 Kudos

JavaScript allows you to just simply add the property to the object:

var arr = [{
  name: "Alice",
  age: 24
}, {
  name: "Alice",
  age: 24,
  height: 175
}]

console.log(arr[0].height) // This will log undefined

arr[0].height = 180

console.log(arr[0].height) // This will log 180