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 :: how to stop iframe video using javascript 
Javascript :: javascript create uuid 
Javascript :: Uncaught ReferenceError: function is not defined at HTMLUnknownElement.onclick 
Javascript :: yarn dev 
Javascript :: 413 payload too large nodejs 
Javascript :: vue timeout 
Javascript :: jsonobject gradle dependency 
Javascript :: how to define emojis from your server in discord.js 
Javascript :: get text inside span vue test utils 
Javascript :: javascript print all items in array 
Javascript :: jquery change selected option 
Javascript :: javascript redirect to 
Javascript :: redirect to homepage javascript 
Javascript :: react form on submit 
Javascript :: function expression and function declaration 
Javascript :: regex for entire word 
Javascript :: how to create click function in javascript 
Javascript :: jquery enable disable textbox 
Javascript :: dummy json data 
Javascript :: how to check if connected to internet js 
Javascript :: filter array of objects to remove duplicate keys 
Javascript :: jquery observe class change 
Javascript :: comma in price js 
Javascript :: js sleep 1 second 
Javascript :: Vanilla JS (on)load with page 
Javascript :: javascript on enter 
Javascript :: create phone number javascript 
Javascript :: system collections generic list to javascript array 
Javascript :: strapi login api 
Javascript :: selecionar valselect2 js 
ADD CONTENT
Topic
Content
Source link
Name
2+6 =