作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我被困在将对象结果的键更改为另一个对象的另一个键,也许我的代码不是动态的,我确实喜欢从这里的人们那里得到一些提示:
function country(arr) {
var obj = {},
temp = {}
for (i of arr) {
if (i.length === 2) {
if (!temp[i[0]])
temp[i[0]] = []
temp[i[0]].push(i[1])
}
if (i.length === 3) {
obj[i[2]] = []
}
}
console.log(obj) // final result
console.log(temp)
}
var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
]
console.log(country(cities))
变量obj
是我想要输出的键,
所以我想要的输出是这样的:
{
Brazil: [ 'Rio de Jeneiro' ],
'United States': [ 'New York', 'Washington DC', 'California' ],
............ rest...
}
是否可以将 temp
对象的键 obj 更改为变量 obj
中的键??
最佳答案
下面使用一些数组方法,即 filter
、map
和 forEach
,根据请求格式化数据。
var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
]
let lookup = {};
cities.filter(city => city[0] === "c").forEach(country => {
let matches = cities
.filter(city => city[0] === country[1])
.map(city => city[1]);
lookup[country[2]] = matches;
});
console.log(lookup);
编辑:这是一个不使用数组函数的解决方案。
var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
];
let lookup = {};
for (let i = 0; i < cities.length; i++) {
// Test if this is a country
if (cities[i][0] === "c") {
// Make sure we have not processed this country before
if (!lookup[cities[i][2]]) {
lookup[cities[i][2]] = [];
let countryCode = cities[i][1];
// Loop through cities again and match country code
for (let j = 0; j < cities.length; j++) {
if (cities[j][0] === countryCode) {
lookup[cities[i][2]].push(cities[j][1]);
}
}
}
}
}
console.log(lookup);
关于javascript - 如何用另一个对象的键更改对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256588/
我是一名优秀的程序员,十分优秀!