PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to append a property to another property of type object in JavaScript

 July 23, 2022     javascript, json, object     No comments   

Issue

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
    }
  }
}

Solution

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)
  }
}



Answered By - Barmar
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing