2017-03-14 10 views
-1
Array.prototype.indicesOf = function (el) { 
    let indices = []; 
    for (var i = this.length - 1; i >= 0; i--) { 
     if (this[i] === el) 
      indices.unshift(i); 
    } 
    return indices; 
} 

class CommentNester { 

    constructor(comments) { 
    this.comments = comments; 
    this.nestedComments = this.nest(); 
    } 

    getComments() { 
    return this.comments; 
    } 

    getNestedComments() { 
    return this.nestedComments; 
    } 

    nest() { 

    const comments = this.comments.slice(); 

    (function appendChildren(parent_id = null) { 

     const childIndices = comments.map(comment => comment.parent_id).indicesOf(parent_id); 

     childIndices.forEach(index => { 
     const child = comments[index]; 

     if (parent_id) { 
      const parentIndex = comments.findIndex(comment => comment.id === parent_id); 
      if (!comments[parentIndex].children) { 
      comments[parentIndex].children = []; 
      } 
      comments[parentIndex].children.push(child); 
     } 

     appendChildren(child.id); 
     }); 

    })(); 

    return comments.filter(comment => comment.parent_id === null); 
    } 

} 

const comments = [{ 
    id: 1, 
    text: "Top level", 
    parent_id: null 
}, { 
    id: 2, 
    text: "Top level", 
    parent_id: null 
}, { 
    id: 3, 
    text: "Reply level 1", 
    parent_id: 1 
}, { 
    id: 4, 
    text: "Reply level 1", 
    parent_id: 2 
}, { 
    id: 5, 
    text: "Reply level 2", 
    parent_id: 3 
}]; 

getComments()は、(それがchildrenを持っている)、元comments配列が変異して示しているが、私はそれを元に滞在したいです。私は.slice()を使ってコピーを作成していますが、なんらかの理由でそれでもまだ突然変異が起こります。なぜどんなアイデア?ここ配列が変異されている()

Codepen:http://codepen.io/anon/pen/QpMWNJ?editors=1010

+0

'.slice()'配列のみの簡易コピーを作成しますを使用してクリーンなアプローチのために行くのjQueryを使用することができます。それは、オブジェクトのコピーを内部に作成しません。 – 4castle

+1

@ 4castle - 代わりに何を使用しますか? – frosty

+0

その他:重複したリンクから: 'const comments = this.comments.map(a => Object.assign({}、a))' – frosty

答えて

0

使用のオブジェクトのマッピング、

const comments = this.comments.slice() 
const cloneComments = comments.map(f => { 
     let o = {} 
     for(var i in f) o[i] = f[i] 
     return o 
    }) 
0

あなたの答えはここにする必要があります - What is the most efficient way to deep clone an object in JavaScript?

あなたはjQueryのJSON.parse(JSON.stringify(obj))解決のために行く避けたい場合はconst comments = JSON.parse(JSON.stringify(this.comments));

注:サイクリックがある場合、これは壊れます。依存

あなたはextend

// Deep copy 
var newObject = jQuery.extend(true, {}, oldObject); 
+0

同じ解決策を再掲載する代わりに、質問を重複としてフラグを立ててください。 – 4castle

関連する問題