Katie
Katie

Reputation: 81

Is there a way to pull a specific key name from an object by using the value it is assigned?

I am creating a new scrabble scorer from an old one. I created an initial object whose keys are scores and the value for each key is an array of letters. This is the old score key.

I am trying to create a function that takes each letter value from the array of values in the old score key and creates a new key for each in a new object (which I have done) and then assigns each letters the point value that was their corresponding key number from the original object.

I'm not sure how to assign the letters the point value they were initially given in the old score key object.

The function I've created:

function transform(oldScoreKey) {
  let newScoreKey = {};
  for (var item in oldScoreKey) {
    for (i = 0; i < oldScoreKey[item].length; i++) {
      newScoreKey[oldScoreKey[item][i]] = Object.keys(oldScoreKey)[0];
    }
  }
  return newScoreKey;
}

The old score key:

const oldScoreKey = {
   1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
   2: ['D', 'G'],
   3: ['B', 'C', 'M', 'P'],
   4: ['F', 'H', 'V', 'W', 'Y'],
   5: ['K'],
   8: ['J', 'X'],
   10: ['Q', 'Z']
};

with this code i am getting the reults { A: '1', E: '1', I: '1', O: '1', etc.}

when i expected to get

{ A: '1', D: '2', J: '8', Q: '10', etc.}

Upvotes: 2

Views: 130

Answers (2)

Shubham
Shubham

Reputation: 1793

// console.log(0.2 + 0.4)

const oldScoreKey = {
   1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
   2: ['D', 'G'],
   3: ['B', 'C', 'M', 'P'],
   4: ['F', 'H', 'V', 'W', 'Y'],
   5: ['K'],
   8: ['J', 'X'],
   10: ['Q', 'Z']
};

const finalObj = {};

Object.keys(oldScoreKey).forEach((key) => {
	oldScoreKey[key].forEach((val) => {
  	// console.log(val, key);
  	finalObj[val] = key;
  });
});


console.log(finalObj);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386883

You could assign item directly as value, without taking the keys.

function transform(oldScoreKey) {
  let newScoreKey = {};
  for (var item in oldScoreKey) {
    for (var i = 0; i < oldScoreKey[item].length; i++) { // declare i otherwise it's global
      newScoreKey[oldScoreKey[item][i]] = item;          // take item
    }
  }
  return newScoreKey;
}

const oldScoreKey = {
   1: ['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'],
   2: ['D', 'G'],
   3: ['B', 'C', 'M', 'P'],
   4: ['F', 'H', 'V', 'W', 'Y'],
   5: ['K'],
   8: ['J', 'X'],
   10: ['Q', 'Z']
};

console.log(transform(oldScoreKey));

Upvotes: 3

Related Questions