Appending new data to object

javascript add object to another object
javascript add to object
add array to object javascript
add property to object javascript
es6 add to object
javascript append to object literal
javascript add kvp to object
javascript object

I'm stuck trying to append new data to an stdClass object that I'm creating for an AMchart

I'm returning all the rows I want from the DB, then creating a new object and looping through the returned array, but rather than appending what I want to the end of the existing object, it just gets overwritten. PHP objects dont have an append or push method, so how do you accomplish this?

Here's what my code looks like. Am I missing something simple?

    $sql = 'SELECT 
            count(*) as clients,
            STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
            SUM(wait_time) as total_wait_time
            FROM tb_by_client
            WHERE status = @qualifier
            GROUP BY Appt_date';

    $rows = $db->fetchAll($sql);
    $chartObject = new stdClass();
    foreach($rows as $row){
        $row->average = round($row->total_wait_time / $row->clients);
        $chartObject->date = $row->date;
        $chartObject->average = $row->average;
    }
    $chartArray[] = $chartObject;
    return json_encode($chartArray);

So instead of getting something that looks like this

[{"date":"2018-10-01","average":12},{"date":"2018-10-02","average":-33},{"date":"2018-10-04","average":23},{"date":"2018-10-05","average":6}]

I get back just a single

[{"date":"2018-10-01","average":12}]

Because each loop overwrites the last key and value

How do you append instead?

Your problem is you overwrite the data without saving it

$chartObject = new stdClass();
foreach($rows as $row){
    $row->average = round($row->total_wait_time / $row->clients);
    $chartObject->date = $row->date;
    $chartObject->average = $row->average;
}
$chartArray[] = $chartObject;

See on each iteration of foreach($rows as $row){ you change the data in $chartObject, but you never save in your $chartArray.

Do this instead

foreach($rows as $row){
    $chartObject = new stdClass(); //new instance of stdClass, obj pass by refrence
    $row->average = round($row->total_wait_time / $row->clients);
    $chartObject->date = $row->date;
    $chartObject->average = $row->average;
    $chartArray[] = $chartObject;
}

Personally I wouldn't even bother with using an object:

foreach($rows as $row){
    $average = round($row->total_wait_time / $row->clients);
    $chartArray[] = ['date'=>$row->date,'average'=>$average];
}

When you JSON Encode an array with string keys, it will make it the correct Javascript Object structure. So there really is no need to keep all those objects in memory and the code is much smaller, cleaner, and easier to read.

One last thing I hinted at in the code, is that objects are pass by reference in PHP (now), and if you don't create a new instance of the object for each iteration, you will actually update all references to the object. This can be illustrated like this:

$obj = new stdClass;

$objects = [];

for($i=0;$i<3;++$i){
    $obj->foo = $i;
    $objects[] = $obj;
    print_r($objects);
}

Output:

Array
(
    [0] => stdClass Object
        (
            [foo] => 0
        )

)
Array
(
    [0] => stdClass Object
        (
            [foo] => 1
        )

    [1] => stdClass Object
        (
            [foo] => 1
        )

)
Array
(
    [0] => stdClass Object
        (
            [foo] => 2
        )

    [1] => stdClass Object
        (
            [foo] => 2
        )

    [2] => stdClass Object
        (
            [foo] => 2
        )

)

Sanbox

Each array is a single iteration of the for loop, this is the same array with another row added after each iteration.

As you can see each copy (its not really a copy) is updated by reference in the array. Basically we have stored the same object (instance ,will call him Bob) 3 times, instead of 3 separate objects (Bob, Alice, John).

If the data you stored was the color of a persons shirt, when Bob puts on a red shirt, he has a red shirt on, but Alice and John don't.

Because of this you need to create a new instance of the object for each iteration and store that.

Hope that helps!

Adding elements to object, To add new items to a plain object use this syntax: var columns = {}; var index = 0; $.each(data, function() { columns[index] = { field : this.field,  As time goes by, new data may appear and needs to be added to the dataset in R. Just like matrices, data frames can be appended using the rbind() function. Adding a single observation Say that Granny and Geraldine played another game with their team, and you want to add the number of baskets they […]

You can do the maths in the SQL and it cuts out the loop altogether...

   $sql = 'SELECT STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
            round(SUM(wait_time)/count(*)) as average
            FROM tb_by_client
            WHERE status = @qualifier
            GROUP BY Appt_date';

    return json_encode($db->fetchAll($sql));

FormData.append(), Anyone know whether it's possible to add an item to a specific position inside an object? So here's the thing: unlike arrays, objects don't have an  The int to Integer conversion is a bit weird indeed, I’d go for: private int[] append(int[] orig, int … append) { int[] result = Arrays.copyOf(orig, orig.length + append.length); System.arraycopy(append, 0, result, orig.length, append.length); return result; } No benchmarking done, but I’d expect direct array copy to perform a bit better, without the need to do the extra conversions.

You're misunderstanding what should be in the loop and what shouldn't.

This should be fine:

$sql = 'SELECT 
        count(*) as clients,
        STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
        SUM(wait_time) as total_wait_time
        FROM tb_by_client
        WHERE status = @qualifier
        GROUP BY Appt_date';

$rows = $db->fetchAll($sql);
$chartArray = [];
foreach($rows as $row){
    $row->average = round($row->total_wait_time / $row->clients);
    $chartObject = new stdClass();
    $chartObject->date = $row->date;
    $chartObject->average = $row->average;
    $chartArray[] = $chartObject;
}
return json_encode($chartArray);

How to add a new item to an object at a specific position with vanilla , Well I'm glad you asked. append is immutable. It never changes any of its arguments, only ever creates new objects that are derived from the  You will see updates in your activity feed. You may receive emails, depending on your notification preferences. I want to append a new element,say 'c', to A, how could I do? I would appreciate if you could help me. Sign in to answer this question. Is there a way to "append to the beginning" of the cell array? Hopefully it's self-explanatory.

Four reasons to use append() instead of Object.assign() and Object , obj − This is the object to be appended in the list. Return Value. This method does not return any value but updates existing list. Example. The following example  Append rows of other to the end of caller, returning a new object. Columns in other that are not in the caller are added as new columns. The data to append. If True, do not use the index labels. If True, raise ValueError on creating index with duplicates. Sort columns if the columns of self and other are not aligned.

Python List append() Method, Columns in other that are not in the caller are added as new columns. Parameters. otherDataFrame or Series/dict-like object, or list of these. The data to append. The events variable starts out as an array, and item 0 of that array is an object that is empty. As you are wanting the checked values to be stored in an array, as [141, 167], here’s how you

pandas.DataFrame.append, variantObj, Specify the variant object to which you want to append data. The Content property is modified to add the new data. contents. Specify the data you  This is actually the correct answer as the others are referring to transforming object into the array, but this way you are keeping it as the object. In the case of the author, its possible that it was better for him to work with the arrays, but this would be the answer on how to append to an object.

Comments
  • $chartArray[] = $chartObject; needs to be inside your loop
  • And $chartObject = new stdClass(); for that matter :)
  • Thanks for the clarification, although Nigel Ren has the shortcut by just editing the query, I appreciate the time you took to show me where I was going wrong. Thanks!
  • I didn't even look at the SQL ... lol. Such as I didn't even notice the original had group by in it. As the question is written it makes more sense to do it in the SQL instead of PHP. Nice answer!
  • You're right, so much simpler that way. I didn't even think to approach it from that angle, thanks for the heads up!