2

I am trying to push the same object into an array with some modification to the object. But when i do modification and push the object the first object which is in array is getting overrided.

var details = [{"name":"john","id":2,"personalEmail":"[email protected]","workEmail":"[email protected]"}];    var searchData = "joh";
var pattern1 = new RegExp("(?:^|[\\s\@])"+searchData, "i");
var data = [];
for(var i=0;i<details.length;i++){
  var name = details[i].name;
  if(pattern1.test(name)){
   var dom = name.replace(name.match(pattern1), '<strong>'+ name.match(pattern1) + '</strong>');
   details[i].name = dom;        
   data.push(details[i]);
   console.log("first ::::"+JSON.stringify(data));
   if(details[i].workEmail != null){
 details[i].personalEmail = details[i].workEmail;
     data.push(details[i]);
     console.log("second::::"+JSON.stringify(data));
   }
  }
}

Here is the fiddle http://jsfiddle.net/LQg7W/2311/. We can see the output in Console (F12 Console tab).

Output Getting:

second::::[{"name":"<strong>joh</strong>n","id":2,"personalEmail":"[email protected]","workEmail":"[email protected]"},{"name":"<strong>joh</strong>n","id":2,"personalEmail":"[email protected]","workEmail":"[email protected]"}]

Expected Output:

second::::[{"name":"<strong>joh</strong>n","id":2,"personalEmail":"[email protected]","workEmail":"[email protected]"},{"name":"<strong>joh</strong>n","id":2,"personalEmail":"[email protected]","workEmail":"[email protected]"}]
Cindrella
  • 1,671
  • 7
  • 27
  • 47

3 Answers3

2

Javascript uses references for objects. As such, in your array, you're adding a reference to your first object, and then you're adding a second reference to the same object. Basically, there's only one object, and two references (kind of like a single file on a filesystem with two shortcuts to it) and so any change you make will appear for all references of that object.

You need to copy your object and then edit the copy. Check out this question: How do I correctly clone a JavaScript object?

....or just use a library like Underscore to accomplish copying. (Edit: Underscore doesn't actually have native support for deep copying, but lodash does - and you should probably be using that anyway.)

Community
  • 1
  • 1
0

Javascript objects are passed by the reference , so the two objects are the same but two references. You need to make a clone of the object for your requirement.
if you are using JQuery ,

var newObject = jQuery.extend(true, {}, details[i]);
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
0

It's the essentials of javascript. Treat all objects as reference type. To do your task you need to create new object and push it into array.

unconnected
  • 991
  • 1
  • 10
  • 21