user1234
user1234

Reputation: 3159

how to replace an element with a specific index in an array of objects-Javascript

I have array of objects:

var arr=[
{name:"d", op: "GTE", field:"ddd"},
{name:"dss", op: "LTE", field:"d4dd"},
{name:"dss", op: "GE", field:"ddddd"}]

I have managed to get index of every array in the element, however I'm not sure how to replace the whole object with new values? ex: at index 2, I want the object to look like this after update:

var arr=[
    {name:"d", op: "GTE", field:"ddd"},
    {name:"dss", op: "LTE", field:"d4dd"},
    **{name:"lithe", op: "GE", field:"34545"}**
]

how can i achieve this?

Upvotes: 6

Views: 20936

Answers (4)

Colin Michael Flaherty
Colin Michael Flaherty

Reputation: 796

As other answers mention, you can easily directly access and reassign, i.e. arr[2]={name:"lithe", op: "GE", field:"34545"}.

However, if you want to be more efficient (i.e. only some fields in the object at arr[2] need to be updated, as is your case), it would be better for you to merge your new object with the one that already exists at arr[2]. To do so, you may Object.assign(arr[2], {name:"lithe", field:"34545"}) (ES5), or arr[2]={...arr[2],...{name:"lithe", field:"34545"}} (ES6).

Upvotes: 1

blurfus
blurfus

Reputation: 14031

You can assign the new element values to replace the existing one in the array. like:

 var newElement = {name:"lithe", op: "GE", field:"34545"};

 arr[2] = newElement;

See demo:

var arr = [{
    name: "d",
    op: "GTE",
    field: "ddd"
  },
  {
    name: "dss",
    op: "LTE",
    field: "d4dd"
  },
  {
    name: "dss",
    op: "GE",
    field: "ddddd"
  }
]
console.log("BEFORE");
console.log(arr);

var newElement = {name:"lithe", op: "GE", field:"34545"};

arr[2] = newElement;
/** 
if you need to loop thru the array and find our element, you can do this 

for(var idx=0; idx < arr.length; idx++){
  // any conditional here
  if( idx === 2 ){
     arr[idx] = newElement;
  }
}

*/
console.log("AFTER");
console.log(arr);

Upvotes: 3

Kamil Leis
Kamil Leis

Reputation: 129

arr[2] = {name:"lithe", op: "GE", field:"34545"}

Upvotes: 4

Antiokus
Antiokus

Reputation: 544

Just use simple array access and reassign at the index

arr[indexValue] = myNewObject

Upvotes: 12

Related Questions