Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing an element in an object array

Tags:

javascript

I want to replace the entire object in an array.

http://jsfiddle.net/CWSbJ/

var array = [ {name: "name1" }, { name: "name2" } ];
var element = array[0];
element = {name: "name3"};
alert(array[0].name);

In this piece of code I would expect the output name3, why can't I replace an entire object in an array like this? And what is the good way to do this?

like image 748
RolandG Avatar asked May 21 '12 10:05

RolandG


People also ask

Can you replace elements in an array?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

How do you replace elements in an array by the elements of another array?

We can use the splice() method to replace a part of array elements with elements from another array. But in this scenario we need to pass the elements as parameters, not the array as parameter. To achieve the above task splice() method except the parameters like (0, anotherArr. Length, 1, 2, 3).

How do you replace an element in an array in C++?

std::replace and std::replace_if in C++void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) first, last : Forward iterators to the initial and final positions in a sequence of elements. old_value : Value to be replaced. new_value : Replacement value.


2 Answers

The correct way is

array[0] = {name: "name3"};

Your existing code does not work as expected because you are taking a referenc* to the first element with

var element = array[0];

and then you are replacing the value of this local variable with another object. This leaves the original array unmodified.

like image 138
Jon Avatar answered Sep 21 '22 01:09

Jon


Try this :

var array = [ {name: "name1" }, { name: "name2" } ];
array[0] = {name: "name3"};
alert(array[0].name);

element is not the actual array - its a copy of the array

like image 20
Manse Avatar answered Sep 21 '22 01:09

Manse