Home > Software design >  How to append a property to another property of type object in JavaScript
How to append a property to another property of type object in JavaScript

Time:07-21

I am trying to figure out how to append a new value to the same property of an object. I have this code below:

let xp_logs = {};
for (let i = 0; i <= rows.length; i  ) {
    if (rows[i]) {
        if(member.roles.cache.find(r => r.id == roles.admin)) {
            xp_logs[todaysDate] = {}
            xp_logs[todaysDate][member[i].displayName] = {id: member[i].user.id, xp: rows[i].xp}
            console.log(member.displayName) // returns multiple names, last name is Henry (from rows)
        }
    }
}
fs.writeFileSync("./xp_logs.json", "\n"   JSON.stringify(xp_logs, null, 2));

The value [member.displayName] changes every for loop, and I want every loop to create a new value within [todaysDate] with [member.displayName] property name.

It currently replaces property names with the next name from the row, instead of adding a new property, and at the end of the for loop, it only saves the last name from the row.

{
  "7/21/2022": {
    "Henry": {
      "id": "331231456712356126",
      "xp": 280
    }
  }
}

However, I want to make it look like this:

{
  "7/21/2022": {
    "Sierra": {
      "id": "123561241241241244",
      "xp": 190
    },
    "Cammy": {
      "id": "556574574574234234",
      "xp": 600
    },
    "Henry": {
      "id": "331231456712356126",
      "xp": 280
    }
  }
}

CodePudding user response:

You're resetting xp_logs[todaysDate] to an empty object each time through the loop. You should only do that if the property doesn't already exist.

Also, for loops should use the condition i < rows.length;, not i <= rows.length;. Array indexes go from 0 to length-1. With this fix you don't need the extra check if (rows[i]), which was only needed to skip the iteration after the end of the array.

let xp_logs = {};
for (let i = 0; i < rows.length; i  ) {
  if (member.roles.cache.find(r => r.id == roles.admin)) {
    if (!xp_logs[todaysDate]) {
      xp_logs[todaysDate] = {};
    }
    xp_logs[todaysDate][member.displayName[i]] = {
      id: member.user.id,
      xp: rows[i].xp
    }
    console.log(member.displayName) // returns multiple names, last name is Henry (from rows)
  }
}

  • Related