5
这段代码是关于从MongoDB获取数据并将'_id'元素改为'id元素。 但我发现对象数组没有改变。JavaScript对象数组没有变化
router.get('/loadList', (req,res) => {
Post.find({}, (err, list) => { //fetching data to list
if(err) {
return res.json({success : false});
} else {
let new_list;
//change _id to id
new_list = list.map((obj) => {
obj.id = obj._id;
delete obj._id;
return obj;
});
console.log(new_list);
/*
// _id is still here and id is not created
[{_id: '58e65b2d1545fe14dcb7aac5',
title: 'asdfassafasdf',
content: 'dfasfdasdf',
time: '2017-04-06T15:13:49.516Z',
writer: { _id: '100975133897189074897', displayName: 'Kiyeop Yang' },
coords: { y: '310.3999786376953', x: '139' },
__v: 0 } ]
*/
但是这个代码工作为我想要什么
let list2 = JSON.parse(JSON.stringify(list));
new_list = list2.map((obj) => {
obj.id = obj._id;
delete obj._id;
return obj;
});
console.log(new_list);
/*
// _id is deleted and id is created
{ title: 'asdfassafasdf',
content: 'dfasfdasdf',
time: '2017-04-06T15:13:49.516Z',
writer: { _id: '100975133897189074897', displayName: 'Kiyeop Yang' },
coords: { y: '310.3999786376953', x: '139' },
__v: 0,
id: '58e65b2d1545fe14dcb7aac5' } ]
*/
return res.json({
success : true,
list
});
}
});
});
我认为它与深浅拷贝有关。 但我不知道究竟是什么原因造成的。
感谢