Javascript 当我不';我不想这样?
我正在从API获取降价,我想在我的vuejs应用程序中使用它 我想访问降价和转换后的数据Javascript 当我不';我不想这样?,javascript,object,Javascript,Object,我正在从API获取降价,我想在我的vuejs应用程序中使用它 我想访问降价和转换后的数据 async getNotes() { var regxHighlights = /id:\b([0-9]+)\b/g; var regxNotes = /id-\b([0-9]+)\b/g; fetch(`/books/${this.id}/notes`).then(res => res.json()).then(res => { var data = res.map(n =
async getNotes() {
var regxHighlights = /id:\b([0-9]+)\b/g;
var regxNotes = /id-\b([0-9]+)\b/g;
fetch(`/books/${this.id}/notes`).then(res => res.json()).then(res => {
var data = res.map(n => {
n.note = converter.makeHtml(n.note)
n.note = n.note.replace(regxHighlights, `<b class="ref noteRef" style="user-select: none;" data="id$1" >id:$1</b>`);
n.note = n.note.replace(regxNotes, `<b class="ref noteRef" style="user-select: none;" data="id-$1" >id-$1</b>`);
return n
})
this.notes = data
this.rawNotes = res
})
},
async getNotes(){
var regxHighlights=/id:\b([0-9]+)\b/g;
var regxNotes=/id-\b([0-9]+)\b/g;
获取(`/books/${this.id}/notes`)。然后(res=>res.json())。然后(res=>{
var data=res.map(n=>{
n、 note=converter.makeHtml(n.note)
n、 note=n.note.replace(regxHighlights,`id:$1`);
n、 note=n.note.replace(regxNotes,`id-$1`);
返回n
})
this.notes=数据
this.rawNotes=res
})
},
问题是
res
已更改!所以data
和res
是一回事。这不应该发生,对吧 听起来,响应是一个对象数组。执行res.map(n
)时,每个n
都是对原始对象之一的引用。例如,在第一次迭代中,n===res[0]
;更改n
将更改res[0]
看起来制作对象的浅层副本应该在这里起作用:
var data = res.map((originalObj) => {
const newObj = { ...originalObject };
newObj.note = converter.makeHtml(n.note)
.replace(regxHighlights,
`<b class="ref noteRef" style="user-select: none;" data="id$1" >id:$1</b>`)
.replace(regxNotes,
`<b class="ref noteRef" style="user-select: none;" data="id-$1" >id-$1</b>`);
return newObj;
})
var data=res.map((originalObj)=>{
const newObj={…originalObject};
newObj.note=converter.makeHtml(n.note)
.更换(regxHighlights,
`id:$1`)
.更换(regxNotes、,
`id-$1`);
返回newObj;
})
因为map
只创建新数组,所以它不会复制元素。n
引用原始对象
:
map()方法创建一个新数组,其中填充了对调用数组中的每个元素调用所提供函数的结果
这是否回答了您的问题?data
和res
是在map
回调中修改的相同引用的不同数组,因此它们实际上是相同的thing@Philres
和data
都是相同的。res
应该是标记,data
应该是HTML,但是y都是htmlYep,对不起。我花了一分钟来看看发生了什么。@Matt解释说,快速解决方案就是复制一个res对象,就像这样让data=object.assign({},res);是的!!!我一直在试着做const newObj={…res};
和循环newObj
,但都不起作用。太好了,