【问题标题】:Update an object from another object using a loop使用循环从另一个对象更新一个对象
【发布时间】:2012-04-05 06:59:42
【问题描述】:

我想从另一个具有相应属性标识符的对象更新对象的属性。希望我能够使用循环来做到这一点,但由于我没有经验,我无法想到如何做到这一点。

我不能说

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 需要由任何标识符表示,但对象中的标识符将始终相同。

【问题讨论】:

标签: javascript loops object properties identifier


【解决方案1】:

排序使用:

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多