2017-08-17 241 views
0

我有一個對象數組,分析也是一個對象數組。如何使用immutability-helper更新數組中的嵌套對象?

const products = [ 
    { 
     id: '111', 
     analysis: [ 
      { id: 1, value: 51 }, 
      { id: 2, value: 40 }, 
      { id: 3, value: 25 } 
     ] 
    }, 
    { 
     id: '222', 
     analysis: [ 
      { id: 1, value: 77 }, 
      { id: 2, value: 99 }, 
      { id: 3, value: 22 } 
     ] 
    } 
] 

我是新來的不變性幫手。我有一個數組operations,它指示如何更新products數組。

const operations = [ 
    { id: '111', analysisId: 1, value: 10 }, 
    { id: '111', analysisId: 3, value: 4 }, 
    { id: '222', analysisId: 3, value: 88 } 
]; 

因此,這意味着我要找個對象與id = 111,然後找到analysisId = 1,終於從51到10,更新值。然後我需要做同樣的事情,其餘2個操作。我不想改變products數組。有人會幫助我嗎?謝謝!

+0

你'products'未初始化爲'Immutable'對象之前找到的指標呢? –

回答

1

據我所知,他們只是做是做更新

operations.map(operation => { 
    var indexOfProduct = products.findIndex(x => x.id === operation.id); 
    var indexOfAnalysis = products[indexOfProduct].analysis.findIndex(a => a.id === operation.analysisId); 
    products = update(products, { 
     [indexOfProduct]: { 
      analysis: { 
       [indexOfAnalysis]: { 
        value: {$set: operation.value} 
        }     
       } 
      } 
     }) 
}); 
+0

謝謝!我無法從他們的文檔中扣除我們應該將indexOfProduct作爲[indexOfProduct]傳遞。 – Dimo