0

Despite answers provided in Modifying a copy of a JavaScript object is causing the original object to change

and

How do I correctly clone a JavaScript object?

I have issues in cloning object.

In this fiddle you will notice that changes in the childObject affects the parent as well https://jsfiddle.net/vpmerr5k/

var obj = { id: { '1': { entry: '1', rowCount: 2 },
 '2': { entry: '2', rowCount: 3 },
 '3': { entry: '3', rowCount: 4 },
 '4': { entry: '4', rowCount: 5 },
 '6': { entry: '6', rowCount: 7 },
 },ip_address: { '200.235.118.96': { entry: '200.235.118.96', rowCount: 2 },
 '1.57.134.207': { entry: '1.57.134.207', rowCount: 3 },
 '116.202.63.225': { entry: '116.202.63.225', rowCount: 4 },
 '176.128.148.225': { entry: '176.128.148.225', rowCount: 5 },
 '144.176.153.177': { entry: '144.176.153.177', rowCount: 6 },
 }
}
var slicedObj = Object.assign({}, obj); 
Object.keys(slicedObj).map(function(keys){  
 Object.keys(slicedObj[keys]).map(function(param){
  if(!(slicedObj[keys][param]["rowCount"]>0 && slicedObj[keys][param]["rowCount"]<4)) {
     delete(slicedObj[keys][param])
 }  })})
console.log(obj)

But In this fiddle the changes dont affect the parentObject (removed the map function) https://jsfiddle.net/5oxducfy/

var obj = { id: { '1': { entry: '1', rowCount: 2 },
 '2': { entry: '2', rowCount: 3 },
 '3': { entry: '3', rowCount: 4 },
 '4': { entry: '4', rowCount: 5 },
 '6': { entry: '6', rowCount: 7 },
 },
ip_address: { '200.235.118.96': { entry: '200.235.118.96', rowCount: 2 },
 '1.57.134.207': { entry: '1.57.134.207', rowCount: 3 },
 '116.202.63.225': { entry: '116.202.63.225', rowCount: 4 },
 '176.128.148.225': { entry: '176.128.148.225', rowCount: 5 },
 '144.176.153.177': { entry: '144.176.153.177', rowCount: 6 },
 }
}
var slicedObj = Object.assign({}, obj); 
Object.keys(slicedObj).map(function(keys){
     delete(slicedObj["id"])
})
console.log(obj)

Is my interpretation right? (Issue being with map function) Is so please suggest a way out.

Community
  • 1
  • 1
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20
  • Except for the academic effect, why are you writing your own object cloning function? – Tomalak Nov 30 '16 at 08:20
  • Sry friend, I dont see any cloning function. I just have a usecase where I need to create child Objects from parent Object. I want to use the cloning the object and editing it later approach. – Rajkumar Somasundaram Nov 30 '16 at 11:50

0 Answers0