我正在为我的循环行为感到困惑,希望你能帮忙翻译一下。这是我读到的 JSON 示例:
[{"type":"robot","town":"NANTES","region":"Ouest","performances":[{"date":YYYY-MM-DD","value":100},{...}],"availability":[{"date":"YYY-MM-DD","value":100},{...}]},{"type":"robot","town":"RENNES","region":"Ouest","performances":[{"date":YYYY-MM-DD","value":100},{...}],"availability":[{"date":"YYY-MM-DD","value":100},{...}]}
我创建了两个对象:
REGIONS = {},TOWNS= {};
这是我收到对象时的函数:
function getRobotsDatas(robotList) {
for (var i = 0; i < robotList.length; i++) {
var robot = robotList[i];
// working on TOWNS object
//I check if the "town" object of TOWNS object already exist
if (TOWNS[robot.town] === undefined) {
// if not, i create it
TOWNS[robot.town] = {};
//then i push performances datas of my robot in my TOWNS.town object
TOWNS[robot.town].performances = robot.performances;
// the same for availability datas
TOWNS[robot.town].availability= robot.availability;
}
// then I work nearly the same way on REGIONS object.
//i check if the "region" object exist in REGIONS object. If not, i create it and add the perf+availability datas of the robot.
if (REGIONS[robot.region] === undefined) {
REGIONS[robot.region] = {};
REGIONS[robot.region].performances = robot.performances;
REGIONS[robot.region].availability= robot.availability;
}
// If the REGIONS.region already exist, i just want to add the datas of performances and availability in the already existing arrays of REGIONS.region (performances[] and availabilities[])
else {
for (var j = 0; j < robot.performances.length; j++) {
REGIONS[robot.region].performances.push(robot.performances[j]);
}
for (var k = 0; k < robot.availability.length; k++) {
REGIONS[robot.region].availability.push(robot.availability[k]);
}
}
}
问题在于对于已经存在的“REGIONS.region”条件也适用于TOWNS。它将机器人的可用性和性能价值添加到具有相同“region”属性值的机器人的TOWNS对象中。 例如,在我开始时给出的示例中,我会在一个新的对象中找到可用性和性能数据:REGIONS.Ouest {performances:[...], availability:[...]},但是我也会在RENNES的perf和availabilities数组中找到NANTES的perf和availibilities数据…而我不希望出现这种情况!
我的条件/循环有什么问题!?