Skip to Content

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

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};

Add a comment
10|10000 characters needed characters exceeded

Related questions

3 Answers

  • Posted on May 11 at 07:33 AM

    Hi,

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

    regards,

    Mateusz

    Add a comment
    10|10000 characters needed characters exceeded

  • Posted on May 11 at 09:28 AM

    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
    Add a comment
    10|10000 characters needed characters exceeded

  • Posted on May 11 at 07:38 AM
    -1

    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

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.