[Solved] adding an object to an existing javascript/JSON array [closed]


As already mentioned in the comments, this an object, not an array (the constructor function is Object and the __proto__ object as well).

If you have numerically consecutive keys, it would be best to keep the objects in an array and then you would be able to .push a new value onto it.

However, if that’s not possible, but you still want to add a new object with an increased key, you have to find the current maximum key first. For example:

function get_max_key(obj) {
    return Math.max.apply(Math, Object.keys(obj));
}

obj[get_max_key(obj) + 1] = new_value;

Alternatively you could just count the number of values in the object (depending on the actual situation and the value of the keys):

function get_number_of_properties(obj) {
    return Object.keys(obj).length;
}

To avoid extracting the keys and process them every time, you could keep the current length or highest key in an extra variable or as a property on the object. For example, you could assign a length property to the object and thus make it an array-like object:

var obj = {
    length: 0
};

The advantage is that you can apply many (if not all) array methods to that object. You could even use Array.prototype.push to add a new property:

[].push.call(obj, new_value);

and it would update the length property for you.

But again, in this case you could just directly use an array instead.


Have a look at MDN – Working with Objects to learn more about objects.

solved adding an object to an existing javascript/JSON array [closed]