尽管在Modifying a copy of a JavaScript object is causing the original object to change
中提供了答案和
How do I correctly clone a JavaScript object?
我在克隆对象时遇到了问题。
在这个小提琴中,您会注意到childObject中的更改也会影响父级 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)
但是在这个小提琴中,这些变化不会影响parentObject(删除了map函数) 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)
我的解释是对的吗? (与地图功能有关) 是的,请建议一个出路。