GreenDome
GreenDome

Reputation: 277

Adding attributes to a JSON file

I have a JSON file with the format below. Each object is a unique with the playerId attribute. The file contains thousands of records. I would like to go through this file and add 2 new attributes to each object with fixed values i.e. "score" : "0" and "maxScore" : "0". Is there an easy way I could do this?

{
  "-Lw9GeAyuqkcLWUywK2R": {
    "playerId": "0a422c4c-8740-4ac3-8bec-7a33ca353534"
  },
  "-Lw9GeB2SjAdiL3X4Kjo": {
    "playerId": "0125bfa3-3403-4a3f-8f9d-f97qwe975644"
  },
  "-Lw9GeB5_MugPmD-qZcy": {
    "playerId": "a382031c-fe90-4782-a50b-039fyytm7866"
  }
}

Upvotes: 0

Views: 296

Answers (1)

Eldar
Eldar

Reputation: 10790

Convert your json into object with JSON.parse then use Object.keys to enumerate keys and modify each property of object with mentioned properties. Then convert back to string

const jsonString = `{
  "-Lw9GeAyuqkcLWUywK2R": {
    "playerId": "0a422c4c-8740-4ac3-8bec-7a33ca353534"
  },
  "-Lw9GeB2SjAdiL3X4Kjo": {
    "playerId": "0125bfa3-3403-4a3f-8f9d-f97qwe975644"
  },
  "-Lw9GeB5_MugPmD-qZcy": {
    "playerId": "a382031c-fe90-4782-a50b-039fyytm7866"
  }
}`;

const obj = JSON.parse(jsonString);
Object.keys(obj).forEach(key=> obj[key] = {...obj[key],maxScore:0,score:0}); // you can also use Object.assign

console.log(obj);

const modifiedJson = JSON.stringify(obj);
console.log(modifiedJson);

Upvotes: 1

Related Questions