0

So this is been giving me a headache for quite a while:

{
  "gravetender": {
    "musicTokens": 2
  },
  "Bob-chan": {
    "musicTokens": 3
  }
}

I simply want to set all the musicTokens to 5, no matter the name. I've tried forEach and for in. This is what changes the musicTokens for a single user for now:

client.profiles [message.author.username].musicTokens = 5;

My client.profiles is my JSON, the message.author.username gets the name and .musicTokens targets the variable.

I'm looking for something like client.profiles.*.musicTokens = 5

thanks

2
  • There is no JSON in your code. Commented Jul 15, 2018 at 20:09
  • awh so I don't know much about the code I wrote there Commented Jul 15, 2018 at 20:11

3 Answers 3

1

Use Object.values() and Array#forEach():

const client = {
  "profiles": {
    "gravetender": {
      "musicTokens": 2
    },
    "Bob-chan": {
      "musicTokens": 3
    }
  }
}

Object.values(client.profiles).forEach(profile => {
  profile.musicTokens = 5
})

console.log(client.profiles)

Sign up to request clarification or add additional context in comments.

Comments

1
 for(const profile of Object.values(client.profiles))
    profile.musicTokens = 5;

Comments

0

There is not a javascript way to do this outside of a potential 3rd party plugin. You'll have to loop over them all like so

Assuming client is a js object

let userNames = Object.keys(client.profiles);
usernames.forEach(username => {
    client.profiles[username].musicTokens = 5;
});

You can use the Map class to iterate over them in place

Assuming client.profiles is Map object

client.profiles.forEach(profile => profile.musicTokens = 5);

Make client.profiles a Map from a js object

client.profiles = new Map(Object.entries(client.profiles));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach

1 Comment

You can use the Map class to iterate over them in place i wanna see that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.