【每日一题】- 2020-08-10 - JS 编程题
azl397985856 opened this issue · 4 comments
azl397985856 commented
// Write a function that takes an object as argument
// Somehow, the properties and keys of the object got mixed up
// Swap the Javascript object's key with its values and return the resulting array
// Tipp: although usually not relevant, mind the order of the properties in the test case outputs
function myFunction(ns) {
}
test case:
myFunction({ bear: 'animal', sow: 'female', boar: 'male', cub: 'young' })
Expected
{ young: 'cub', male: 'boar', female: 'sow', animal: 'bear' }
myFunction({ sheep: 'animal', ewe: 'female', ram: 'male', lamb: 'young' })
Expected
{ young: 'lamb', male: 'ram', female: 'ewe', animal: 'sheep' }
myFunction({ whale: 'animal', cow: 'female', bull: 'male', calf: 'young' })
Expected
{ young: 'calf', male: 'bull', female: 'cow', animal: 'whale' }
你可以去 https://www.jschallenger.com/javascript-objects/swap-object-keys-values/challenge?id=5f1043abbd87ab5028fee12e 在线检查自己的答案。
azl397985856 commented
My Accepted One Line Solution With Entries API
Code
function myFunction(ns) {
return Object.fromEntries(Object.entries(ns).reverse().map(entry => entry.reverse()))
}
suukii commented
const myFunction = obj => {
const res = {};
const entries = Object.entries(obj).reverse();
for (const [key, value] of entries) {
res[value] = key;
}
return res;
};
lxhguard commented
function myFunction(ns) {
const keys = Object.keys(ns);
const values = Object.values(ns);
const obj = {};
for(let i = values.length - 1; i >= 0; i--){
obj[values[i]] = keys[i];
}
return obj;
}
stale commented
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.