Answers for "reverse key and value in object js"

0

reverse key and value in object js

//The concise way by using ES6 syntax like this.

const obj = {A : 1, B : 2, C : 3, D : 4}
 function objectFlip(obj) {
     return Object.entries(obj).reduce((acc, [key, value]) => (acc[value] = key, acc), {})
 }
console.log('input:  ',obj);
console.log('output: ',objectFlip(obj));



static objectFlip(obj) {
  const ret = {};
  Object.keys(obj).forEach(key => {
    ret[obj[key]] = key;
  });
  return ret;
}
//Or using Array.reduce() & Object.keys()

static objectFlip(obj) {
  return Object.keys(obj).reduce((ret, key) => {
    ret[obj[key]] = key;
    return ret;
  }, {});
}
//Or using Array.reduce() & Object.entries()

static objectFlip(obj) {
  return Object.entries(obj).reduce((ret, entry) => {
    const [ key, value ] = entry;
    ret[ value ] = key;
    return ret;
  }, {});
}
Posted by: Guest on August-02-2021
0

reverse keys and values in object javascript

var object = { 'a': 1, 'b': 2, 'c': 1 };
//This uses the package lodash

  _.invert(object);
  // => { '1': 'c', '2': 'b' }

  // with `multiValue`
  _.invert(object, true);
  // => { '1': ['a', 'c'], '2': ['b'] }
Posted by: Guest on April-06-2020

Code answers related to "reverse key and value in object js"

Code answers related to "Javascript"

Browse Popular Code Answers by Language