javascript - 数组 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);
});
我觉得我错过了一些简单的东西......有什么想法吗?
解决方案
您只需要在尝试创建对象之前检查对象是否已经存在(从而覆盖之前的对象):
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);
推荐阅读
- angular - 由 adapter.updateOne 引起的 ngRX 无限循环
- sql - SQL查询根据类别列查找连续的局部最大值、最小值
- python - Dynamodb 和 Boto3,在扫描中链接多个条件
- image - 更新已提交的 docker 容器的基础镜像
- typescript - 代表函数,它接受一个对象数组并返回一个具有所有键并集的单个对象
- nvidia - vulkaninfo 失败并显示 VK_ERROR_INITIALIZATION_FAILED
- python - 滚动窗口和应用:如何使用窗口中的两列
- snowflake-cloud-data-platform - 如何增加雪花中的可变大小限制?
- c++ - 学习 C++ 并在将类接口与实现分离时遇到问题
- spring - WEB-INF 未添加到 SpringBoot jar