Pushing a multiple-attributed item to an array JAVASCRIPT

19,525

Solution 1

you are pushing a string into the array. if you want to push another object into the array, then do so by

newCircles.push( {
  num: newCircles.length,
  name: 'title ' + newCircles.length,
  x: newCircles[chosenCircle].x,
  y: newCircles[chosenCircle].y,
  color : "#7f38a7",
  r: newCircles[chosenCircle].r
} );

Solution 2

You're using a string, but what you want to use is an object initializer (frequently called an object literal), just like you did when you initialized your array:

newCircles.push({
    num:   newCircles.length,                // Or you more likely want `newCircles.length + 1`
    name:  "title " + (newCircles.length),   // Again, probably +1
    x:     newCircles[chosenCircle].x,
    y:     newCircles[chosenCircle].y,
    color: "#7f38a7",
    r:     newCircles[chosenCircle].r
});

(There's also no reason for passing it through $().)

As when you initialized your array, the tokens to the left of the : are the property names, and the value of the expressions on the right will be assigned as those properties' values.

Solution 3

Try this instead

newCircles.push( { num:   newCircles.length, 
                   name:  "title "+ newCircles.length, 
                   x:     newCircles[chosenCircle].x, 
                   y:     newCircles[chosenCircle].y, 
                   color: "#7f38a7", 
                   r:     newCircles[chosenCircle].r 
              }); 
Share:
19,525
Feeney
Author by

Feeney

Updated on June 28, 2022

Comments

  • Feeney
    Feeney almost 2 years

    I have an array set out like this:

    var newCircles = [{
        num: 0,
        name: "title0",
        x: 280,
        y: 200,
        color: "#555555",
        r: 60
    },
    {
        num: 1,
        name: "title1",
        x: 480,
        y: 200,
        color: "#555555",
        r: 80
    }];
    

    And I'm trying to push new set of information like this:

    $(newCircles).push(', { num: "'+newCircles.length+'", name : "title "'+(newCircles.length)+'", x : "'+newCircles[chosenCircle].x+'", y : "'+newCircles[chosenCircle].y+'", color : "#7f38a7", r : "'+newCircles[chosenCircle].r+'" }');
    

    But it's not working. Anyone have any suggestions?