首页 > 解决方案 > 数组 forEach 在最后一次迭代中覆盖对象的值

问题描述

我正在遍历文件名数组,拆分名称并将数据存储在一个对象中。用于测试目的的两个文件名是相同的,除了周“数字”应该创建两个单独的周。问题是第一个条目被最后一次迭代覆盖,所以我最终只得到了第 2 周的条目。

编码:

const planList = [
    'military_greekHero_achilles_week_1.htm',
    'military_greekHero_achilles_week_2.htm'
];

var _completePlan = {};

planList.forEach(_plan => {

// Pull data from the file name formated: target_series_title_overview/week_weekNum.htm
    let _planPieces = _plan.split('.')[0].split('_'),// Drop the .htm
        _planTarget = _planPieces[0],
        _planSeries = _planPieces[1],
        _planTitle = _planPieces[2],
        _planOverview = _planPieces[3],
        _planWeek = _planPieces[4];

    _planOverview = _planOverview == 'overview' ? true : false;
    
// Start Building Plan Object
    _completePlan[_planTitle] = {
        info: {},
        weeks: {}
    }

// _planWeek logs 1 and 2 while iterating but entry for .weeks.1 is overwritten with .weeks.2
    _completePlan[_planTitle].weeks[_planWeek] = {
        sn: { inactive: true },
        mo: { inactive: true },
        tu: { inactive: true },
        we: { inactive: true },
        th: { inactive: true },
        fr: { inactive: true },
        st: { inactive: true }
    }
});

console.log(_completePlan);
});

我觉得我错过了一些简单的东西......有什么想法吗?

标签: javascriptarraysforeach

解决方案


您只需要在尝试创建对象之前检查对象是否已经存在(从而覆盖之前的对象):

if (!_completePlan.hasOwnProperty(_planTitle)) {
    _completePlan[_planTitle] = {
      info: {},
      weeks: {}
    }
  }

我还添加了一些重组语句,有助于减少一些代码:

let [_planTarget, _planSeries, _planTitle, _planO, _planWeek] = _plan.split('.')[0].split('_'), // Drop the .htm
_planOverview = _planO === 'overview' ? true : false;

const planList = [
  'military_greekHero_achilles_week_1.htm',
  'military_greekHero_achilles_week_2.htm'
];

var _completePlan = {};

planList.forEach(_plan => {

  // Pull data from the file name formated: target_series_title_overview/week_weekNum.htm
  let [_planTarget, _planSeries, _planTitle, _planO, _planWeek] = _plan.split('.')[0].split('_'), // Drop the .htm
    _planOverview = _planO === 'overview' ? true : false;

  // Start Building Plan Object
  if (!_completePlan.hasOwnProperty(_planTitle)) {
    _completePlan[_planTitle] = {
      info: {}, weeks: {}
    }
  }

  _completePlan[_planTitle].weeks[_planWeek] = {
    sn: { inactive: true},
    mo: { inactive: true},
    tu: { inactive: true},
    we: { inactive: true},
    th: { inactive: true},
    fr: { inactive: true},
    st: { inactive: true}
  }
});

console.log(_completePlan);


推荐阅读