作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个由一些随机城市名称组成的数组,另一个由各个城市的源和目的地组成的json对象数组,但是各个城市的这个路线数组不是按顺序排列的。我需要按照他们访问的顺序排列,我无法做出逻辑..请帮助..
城市数组(动态大小):
var CITIES = ["PARIS","LONDON","DELHI","SINGAPORE","DUBAI"]
路由的 Json 数组(随机序列):
var CITY_ROUTE = {"ROUTE":[
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"},
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
]};
/Required to Rearange the Json Object in Visiting sequence where Starting City will have null PREVIOUS_CITY value and Last City will have null NEXT_CITY Value/
var CITY_ROUTE_IN_SEQUENCE = {"ROUTE":[
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"}
]};
最佳答案
var CITY_ROUTE = {
"ROUTE": [
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"},
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
]
};
var map = {};
var point = '';
CITY_ROUTE.ROUTE.forEach(r => {
map[r.CURRENT_CITY] = r;
if (!r.PREVIOUS_CITY) {
point = r.CURRENT_CITY;
}
});
CITY_ROUTE.ROUTE = [];
while(point) {
CITY_ROUTE.ROUTE.push(map[point]);
point = map[point].NEXT_CITY;
}
console.log(JSON.stringify(CITY_ROUTE));
关于javascript - 如何在 Javascript 中从 Json 数组创建路线 Path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959376/
我是一名优秀的程序员,十分优秀!