[英]Remove JSON parent object after changing the location of all children
我正在嘗試制作一個通用的JSON函數,該函數將發送源,目標,以及在完成后是否應刪除空父對象。 問題是我不確定父對象為空並通過循環完成后如何刪除。
我的代碼成功地帶走了孩子並搬走了孩子,並從當前父母中刪除了孩子。 我面臨的問題是嘗試在完成后刪除父項本身。
let j = {
'test': 'test',
'remove': { 'string1' : 'hello', 'string2' : 'world' }
}
moveAll(j.remove,j,true);
function moveAll(src, dst, del) {
del = del || false;
for ( let item in src ) {
dst[item] = src[item];
if(del) {
delete src[item];
}
}
}
通過上面的代碼,我試圖取出remove的內容並將其放置在主要對象的位置。
因此,如果它按預期工作,它將像這樣。
let j = {
'test': 'test',
'string1' : 'hello',
'string2' : 'world'
}
這就是我目前得到的。 我嘗試使用delete src
,但是src僅包含remove的內容,而不包含本身。 所以我想知道是否有一種訪問父級的方法。
let j = {
'test': 'test',
'remove': { },
'string1' : 'hello',
'string2' : 'world'
}
這只是我想做的基本想法,所以我知道仍然有很多事情要做。 但是我嘗試查找此問題,但找不到解決方案。
提前致謝!
您不能從moveAll
函數中刪除父moveAll
(按編寫的方式),因為它沒有對j
對象的任何引用。 (您傳入j.remove
,但它本身沒有j
。)
這將工作:
moveAll(j, 'remove', j, true);
function moveAll(obj, key, dst, del) {
src = obj[key]
del = del || false;
for ( let item in src ) {
dst[item] = src[item];
if(del) {
delete src[item];
}
}
if (del)
delete obj[key]
}
現在,您的函數可以訪問父對象,並且可以輕松地在末尾delete obj[key]
。
一種選擇是遍歷dst
所有鍵,並檢查它們中的任何一個是否指向src
。 如果是,請從dst
刪除該密鑰(請注意,這假定src
是dst
的直接子代)。
function moveAll(src, dst, del) { del = del || false; for (let item in src) { dst[item] = src[item]; } if (del) { for (let k in dst) { if (dst[k] === src) delete dst[k]; } } } let j = { 'test': 'test', 'remove': { 'string1': 'hello', 'string2': 'world' } } moveAll(j.remove, j, true); console.log(j);
一旦將它們傳遞到函數src和dst中,它們就是兩個不同的對象,因此在src上使用delete不會買任何東西。 您需要像下面一樣刪除dst.remove,但是您需要找到一種在函數中引用它的方法。
let j = {
'test': 'test',
'remove': { 'string1' : 'hello', 'string2' : 'world' }
}
moveAll(j.remove,j,true);
function moveAll(src, dst, del) {
del = del || false;
for ( let item in src ) {
dst[item] = src[item];
if(del) {
//delete src[item];
}
}
delete dst.remove;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.