在JavaScript中交换Object的键值

fdbelqdn  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(139)

我正在尝试交换对象的键和值。我在js fiddle上写了代码,请检查link
没有输出我正在使用以下写代码到html

document.getElementById("demo").innerHTML = out;

谁能告诉我哪里出错了吗?

oalqel3c

oalqel3c1#

你有几个小毛病。我把你的小提琴修好了:

var out='';
var car = {type:"Fiat", model:500, color:"white"};

// BUG #2 -- argument should be obj here not car as you use obj as variable inside
var invert = function (obj) {

  var new_obj = {};

  for (var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
        var value = obj[prop];
      new_obj[value] = prop;
    }
  }

  // BUG #3 need to return the new_obj  
  return new_obj;
};

// BUG #1 -- need to pass car to invert() here! 
for (var value in invert(car)) {
  out += value + ' ';
}
document.getElementById("demo").innerHTML = out;

JSF中间文件:http://jsfiddle.net/o1dcaw8j/2/

pwuypxnk

pwuypxnk2#

最短的两个解决方案Vanilla JavaScript

const objData = {
  type:"Fiat",
  model:500,
  color:"white"
}

// For
let swapObj = {}
for ( let ep in objData){
  swapObj.[objData[ep]] = ep;
}
console.log( swapObj );

// .reduce
const swapObj2 = Object.keys( objData ).reduce(function(obj, key) {
  obj[ objData[key] ] = key;
  return obj;
}, {});
console.log( swapObj2 );

相关问题