2012-03-20 142 views
1

我想更新另一個對象的屬性,該對象將具有相應的屬性標識符。希望我能夠使用循環來做到這一點,但由於缺乏經驗,我無法考慮如何做到這一點。使用循環更新另一個對象的對象

我不能隨便說

object1 = object2; 

因爲對象的數組被連接在一起。

我現在有這個樣子的:

if (direction === 'forw') 
{ 
    renderedCharts.electric.real.full = renderedCharts.electric.real.full.concat(newChartData.electric.real); 
    renderedCharts.electric.budget.full = renderedCharts.electric.budget.full.concat(newChartData.electric.budget); 

    renderedCharts.gas.real.full = renderedCharts.gas.real.full.concat(newChartData.gas.real); 
    renderedCharts.gas.budget.full = renderedCharts.gas.budget.full.concat(newChartData.gas.budget); 
} 
else if (direction === 'back') 
{ 
    for (var index in newChartData) // get the length of the arrays returned (all arrays will have the same number of elements 
    { 
     dataOffset += newChartData[index].real.length; 
     break; 
    } 

    renderedCharts.electric.real.full = newChartData.electric.real.concat(renderedCharts.electric.real.full); 
    renderedCharts.electric.budget.full = newChartData.electric.budget.concat(renderedCharts.electric.budget.full); 

    renderedCharts.gas.real.full = newChartData.gas.real.concat(renderedCharts.gas.real.full); 
    renderedCharts.gas.budget.full = newChartData.gas.budget.concat(renderedCharts.gas.budget.full); 
} 

electricgas需要通過任何標識來表示,但是在對象標識符將始終是相同的。

+1

使用'renderedCharts [electric_or_gas_or_any_variable] .real.full = ...' – 2012-03-20 18:59:00

+0

見[此相關的問題和答案(http://stackoverflow.com/questions/9709130/使用到的javascript對象-擷取值/ 9709167#9709167) – jbabey 2012-03-20 19:00:17

回答

0

排序利用:

if (direction === 'forw') 
{ 
    for (var property in renderedCharts) 
    { 
     renderedCharts[property].real.full = renderedCharts[property].real.full.concat(newChartData[property].real); 
     renderedCharts[property].budget.full = renderedCharts[property].budget.full.concat(newChartData[property].budget); 
    } 
} 
else if (direction === 'back') 
{ 
    for (var property in newChartData) 
    { 
     dataOffset += newChartData[property].real.length; 
     break; 
    } 

    for (var property in renderedCharts) 
    { 
     renderedCharts[property].real.full = newChartData[property].real.concat(renderedCharts[property].real.full); 
     renderedCharts[property].budget.full = newChartData[property].budget.concat(renderedCharts[property].budget.full); 
    } 
}