azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.83k stars 260 forks source link

【每日一题】- 2020-08-10 - JS 编程题 #144

Closed azl397985856 closed 3 years ago

azl397985856 commented 4 years ago

// 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 4 years ago

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 4 years ago
const myFunction = obj => {
    const res = {};
    const entries = Object.entries(obj).reverse();
    for (const [key, value] of entries) {
        res[value] = key;
    }
    return res;
};
lxhguard commented 4 years ago
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[bot] commented 3 years ago

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.