2

I have a array of json objects in jquery . I want to duplicate a object and then replace key value in original object on the basis of if condition . but every time i replaced the value in single object then it replaced the values in both objects . I only want to replace in one i.e original I have used break and return false statements but dont work.

var index=getIndex(class_id,teacher_id);

    finalJson[index]['teacher_name']='asad';

function getIndex(class_id,teacher_id){
    for(var it in finalJson){
    if(finalJson[it]['class'] == class_id && finalJson[it]['type'] == 'c'){
        finalJson.push(finalJson[it])
        return it;
        }
    }
}

please anybody help here is if condition . Thanks in advance.

Asad
  • 3,070
  • 7
  • 23
  • 61

2 Answers2

4

When you do finalJson.push(finalJson[it]) you are pushing the reference to old object again in the array. So, any operation done on one reference will be performed on the object to which new reference is pointing to. Which is why you need to create a new object using the properties of old one (using Object.create) and then push it.

replace

finalJson.push(finalJson[it])

with (don't use this option)

finalJson.push(Object.create(finalJson[it]))

or a slower but deep-copy option

finalJson.push(JSON.parse(JSON.stringify(finalJson[it])));
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • `Object.create(finalJson[it])` will not clone the object only create new object with prototype of old object, so each time old object change new object will change too. – jcubic Mar 14 '16 at 15:50
  • @jcubic I know that it will not do deep cloning but in this case deep cloning isn't required as it seems OP's json isn't of multi level. I have given another option anyways. – gurvinder372 Mar 14 '16 at 16:00
  • `Object.create(finalJson[it])` is simply wrong becuase it will work like cloning a reference or assign object to different variable `a = finalJson[it]` if you change `a` it will change `finalJson[it]` too. The same happen with prototype. it's not cloning at all. – jcubic Mar 14 '16 at 16:06
  • @jcubic as per the spec https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create new object is created with the same properties. – gurvinder372 Mar 15 '16 at 05:13
  • New object is created but the prototype is taken from old object so if you change old object new object will be modified. take a look that this https://jsfiddle.net/smfs8f58/ – jcubic Mar 15 '16 at 08:34
  • @jcubic okay, got it. Updating my answer to remove the first option. Second one should still work though. Thanks for correction. – gurvinder372 Mar 15 '16 at 08:38
1

When you copy the object to a new variable, you are creating a reference. You need to create a new object to prevent this, otherwise the changes applied to one object will apply to the other.

millerbr
  • 2,951
  • 1
  • 14
  • 25