Home > OS >  How to replace a value in dictionary in Javascript
How to replace a value in dictionary in Javascript

Time:11-02

I'm trying to change the value in userInfo with userArray. I tried to change the first value of dictionary by writing Object.values(userInfo)[0] = userArray[0] but it didn't work. Is there another way to change values in a dictionary?

let userInfo = {'John': money(),'Mary': money(),'Bob': money()}

console.log('Before Dictionary:',userInfo)

let total = 0
let userArray = Object.values(userInfo); //To get dictionary values into array
userArray.forEach(doubleMoney) //Multiply array values by 2

function money(){
    randomMoney = Math.floor(Math.random() * 1000000);
    return randomMoney
}
function doubleMoney(element,index,array){
    array[index] = element * 2
}

Object.values(userInfo)[0] = userArray[0] //Change the first value of dict to first value of array

console.log('Mutiplied array: ',userArray)
console.log('After Dictionary: ',userInfo);

CodePudding user response:

You can use the Destructuring Assignment

const first_dict = { 'key_one': 'value_one', 'key_two': 'value_two' } 
const second_dict = { 'key_one': 'value_from_second_dict', 'key_three': 'value_three' }

const accumulative = {
  ...first_dict,
  ...second_dict
}

console.log(accumulative)

CodePudding user response:

The reason why your code doesn't work is because the values are primitives e.g. numbers, so when you create userArray you simply get a new array of numbers. Changing them has no impact on userInfo it contains no references to the userInfo, only values.

So to change the value in userInfo:

// Note that heys are not guaranteed to be ordered so you need to track this yourself
// See https://stackoverflow.com/q/5525795/885922
userInfo[firstKey] *= 2;

To change all the values, use for... in:

for (let user in userInfo) {
    userInfo[user] *= 2;
}

For more info, I recommend reading Is JavaScript a pass-by-reference or pass-by-value language?.

CodePudding user response:

Assignment operator '=' is used to assign values to variables. In your case Object.values(userInfo)[0] will return the value, which can't be assigned to another value (userArray[0]).

You can try the following solution:

Object.keys(userInfo).forEach((key, index) => {
    userInfo[key] = userArray[index] 
});

console.log(userInfo);
  • Related