Return a new object with the given key and its value flipped

As the title says, I am trying to return a new object with the given key and its value flipped and leave all the other key/value pairs unchanged.

Here is what I have so far:

function swapKeyAndValue(obj, key) {
  
  const result = [];
  for (const property in obj) {result.push(obj); }
  return result;
}

var instructor = { name: 'Elie', job: 'Instructor' };

console.log(
  swapKeyAndValue(instructor, 'name'),
  swapKeyAndValue(instructor, 'job')
  );

There is no need for a loop here. Instead, grab the value of the current key using bracket notation, then set the new key (which is the value) and set the new value to the key passed through. You'll then need to delete the old key which you passed through from the object like so:

function swapKeyAndValue({...obj}, key) { // {...obj} will copy the object (so it doesn't change the object passed through directly)
  if (obj.hasOwnProperty(key)) { // check if key is in the object
    const new_key = obj[key]; // grab value
    obj[new_key] = key;
    delete obj[key];
  }

  return obj;
}

const instructor = {
  name: 'Elie',
  job: 'Instructor'
};

console.log(
  swapKeyAndValue(instructor, 'name'),
  swapKeyAndValue(instructor, 'job')
);

Swap key with value JSON, forEach(key => { ret[obj[key]] = key; }); return ret; } In ES6/ES2015 you can combine use of Object.keys and reduce with the new Object.assign function,� In the loop, we’ll create a new key from the value of the key in the original object. We’ll assign the value of that key the property we’re currently looking at in our iteration. That’s all there is to inverting the keys and values! Of course, we’ll return the newly generated object. Use Cases. Okay, so we can invert k, v pairs.

This one works!

function swapKeyAndValue (obj, key) {
const newObj = {};
for (let keys in obj) {
if (keys === key) {
  newObj [obj[keys]] = key;
}
if (keys !== key) {
  newObj[keys] = obj[keys];
}
}
return newObj;

}
var instructor = { name: 'Elie', job: 'Instructor' };
swapKeyAndValue(instructor, 'name');

Object.fromEntries(), fromEntries() method transforms a list of key-value pairs into an of key-value pairs and returns a new object whose properties are given fromEntries , its reverse method Object.entries() , and array manipulation methods,� This approach inverts the object, swapping keys for values, and then finds the key by looking up the value on the new (inverted) object. If the key isn't found then false is returned, which I prefer over undefined, but you could easily swap this out in the third parameter of the _.get method in getKey().

You created a function which creates a new array,

but as I understand you want to change the specific object structure

so this code is the way to do so:

function swapKeyAndValue(obj, key) {
  value = obj[key]
  if (value){
    obj[value]=key
    delete obj[key]
  }
}

var instructor = { name: 'Elie', job: 'Instructor' };

 swapKeyAndValue(instructor, 'name')
console.log(instructor);
 swapKeyAndValue(instructor, 'Elie')
console.log(instructor);
 swapKeyAndValue(instructor, 'name')
console.log(instructor);

Object.entries(), The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as var ownProps = Object.keys( obj ), i = ownProps.length, resArray = new Array(i);� However, BidiMap imposes a 1:1 relationship between its keys and values. If we try to put a key-value pair for which the value already exists in the Map, it removes the old entry. In other words, it updates the key against the value. Also, it requires a larger amount of memory for keeping the reverse map.

actually what you want is really easy to achieve using reduce

function swapKeyAndValue(obj, key) {
  const reducer = (accum, ck) => {  // ck is the current key
    if (ck === key) {          // if ck is the key that we want to swap, we enter.
      const val = obj[ck];     // take the value to a var
      accum[val] = key;       // then we swap it
    } else {
      accum[ck] = obj[ck];    // we dont swap anything...
    }
    return accum;             // we return our partially build obj
  }
  return Object.keys(obj).reduce(reducer, {});
}

var instructor = {
  name: 'Elie',
  job: 'Instructor'
};

console.log(
  swapKeyAndValue2(instructor, 'name'),
  swapKeyAndValue(instructor, 'job')
);

Objects, In JavaScript, objects penetrate almost every aspect of the language. A property is a “key: value” pair, where key is a string (also called a let user = new Object ( ) ; // "object constructor" syntax let user = { } ; // "object literal" syntax these properties are all right let obj = { for : 1 , let : 2 , return : 3 } ; alert� Then fetch the key using the position of the value in the val_list. As key at any position N in key_list will have corresponding value at position N in val_list. Method #2: Using dict.item() We can also fetch key from a value by matching all the values and then print the corresponding key to given value.

Here is another simple way to solve this problem using a For Loop & 2 If Statements!

function swapKeyAndValue(obj, swappedKey){
  var result = {};
  for(var key in obj){
  if(key === swappedKey){
    result[obj[key]] = swappedKey;
  }
    if(key !== swappedKey){
    result[key] = obj[key];
  }
}
return result;

}

ImmutableListMultimap (Eclipse Collections, Returns a view of all values associated with the given key. Creates a new instance of the same implementation type, using the default capacity and growth � {note} Methods that mutate the collection (such as shift, pop, prepend etc.) are not available on the LazyCollection class.. Lazy Collection Methods. In addition to the methods defined in the Enumerable contract, the LazyCollection class contains the following methods:

Documentation, Creates an array of array values not included in the other given arrays using SameValueZero for equality comparisons. toPairs ; this method returns an object composed from key-value pairs . (Function): Returns the new flipped function. The value of the dimension is returned by the object. Now in the Main method there are two objects named as t1 and t2 . In this statement Triangle t2 = t1.newdimension(2); , the previous dimension, i.e. 2 and 8 of the triangle is enlarged by 2 and the result assigned to the t2 object.

Collections, We'll use the collect helper to create a new collection instance from the array, run the helper returns a new Illuminate\Support\Collection instance for the given array. [flatMap](#method-flatmap) [flatten](#method-flatten) [flip](#method-flip) This method will return the key / value pairs in the original collection that are not� Returning Object as argument . Syntax: object = return object_name; Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type ‘Example'(i.e., class name) whose value is stored in E3.

Rogue Wave Views Foundation Package API Reference Guide, Checks whether this object's class is a subclass of a given parent class. virtual void, print Flips a graphic object. virtual void Retrieves the property value associated with the key in this object's class. static const getStream() >> pos; // Read the position field return new IlvLabel(pal->getDisplay(), pos, IlvReadString( file. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL , the new instance will be empty. An array converts to an object with properties named by keys and corresponding values.

Comments
  • that makes sense! Thank you
  • @CodyWirth no worries
  • Hi, welcome to SO, please do add some more details to the answer, as to what this code snippet would do to help the person asking the question or anyone in the future reading the question and answer to get a clear picture :)