【问题标题】:How do I reverse the Object in Javascript [duplicate]如何在Javascript中反转对象[重复]
【发布时间】:2021-12-29 09:59:22
【问题描述】:

如何转换:

{one:1,two:2,three:3,four:4}

到这里:

{1:'one',2:'two',3:'tree',4:'four'}

我试过这个:

Array.prototype.reverse.call({1:'one', 2:'two', 3:'tree',4:'four' length:5});

但这会扭转整个事情,这是我不想要的。有人有什么建议吗?

【问题讨论】:

    标签: javascript node.js arrays javascript-objects


    【解决方案1】:

    您可以使用for... in 循环来执行此操作,将每个属性的键分配给结果对象中的值。

        
    let o = {one:1,two:2,three:3,four:4};
    let result = {};
    for(let key in o) {
        result[o[key]] = key;
    }
    console.log('Result:', result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    您也可以使用Array.reduceObject.entries() 来获得您想要的结果:

        
    let o = {one:1,two:2,three:3,four:4};
    let result = Object.entries(o).reduce((acc, [key,value]) => { 
        return { ...acc, [value]: key };
    }, {});
    console.log('Result:', result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案2】:

      您可以将Object.fromEntries()Object.entries()Array.prototype.map 组合使用来反转键值对。

      const obj = {one:1,two:2,three:3,four:4};
      
      const reverseObj = Object.fromEntries(Object.entries(obj).map(([key, value]) => [value, key]));
      
      console.log(reverseObj);

      【讨论】:

        【解决方案3】:

        您可以使用Object.entries() 将键/值对放入数组中,然后使用.reduce() 构造一个新对象:

        function invertObject(obj) {
          return Object.entries(obj).reduce(function(newObj, pair) {
            newObj[pair[1]] = pair[0];
            return newObj;
          }, {});
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-11
          • 2015-01-02
          相关资源
          最近更新 更多