Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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;
  }, {});
}
Comment

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'] }

Comment

PREVIOUS NEXT
Code Example
Javascript :: trigger a function inside child from parent vue 
Javascript :: jquery get position of element 
Javascript :: remove all sign that is not a-b in string js 
Javascript :: replace is not working in javascript 
Javascript :: js reverse linked list 
Javascript :: json stands for 
Javascript :: js add multiple element to document 
Javascript :: js int to string base 
Javascript :: max js 
Javascript :: kendo datasource get 
Javascript :: google script check if cell is empty 
Javascript :: encryptedfields mongoose-encrypt 
Javascript :: js push array into array 
Javascript :: trigger jquery 
Javascript :: math power javascript 
Javascript :: javascript change css opacity duration 
Javascript :: concat class name vue js 
Javascript :: var x = 
Javascript :: add google analytics to react 
Javascript :: parse date without timezone javascript 
Javascript :: get url of website javascript 
Javascript :: jquery on change on multiple elements 
Javascript :: console log 
Javascript :: react hide element 
Javascript :: How to make HTML input tag only accept numerical values? in jsx 
Javascript :: inherit javascript 
Javascript :: Comparing and Filtering two arrays 
Javascript :: how to include script file in javascript with javascript 
Javascript :: javascript get current window location without parameters 
Javascript :: angularjs 1.5.6 cdn 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =