Reputation: 557
So to explain this, I am creating a JSON object and with this object, I would like to be able to modify it like a PHP array. Meaning I can add more values into the array at any given time to a key.
For instance, PHP would be like this:
$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
You can see that PHP can add more data into the array object with the key of 'car'. I'm wanting to do that same thing for a JSON object except it may not always be as a string for the key.
function count(JSONObject) {
return JSONObject.length;
}
test = {};
test[100] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
I know you can create new objects like this, but this is not what I'm wanting to do.
test[101] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
This is what I can think of but I know it doesn't work:
test[100][count(test[100])] { // Just a process to explain what my brain was thinking.
charge: "N",
mannum: "7",
canUse: "N"
}
I'm expecting the results to be somewhat like this (It also doesn't have to look exactly like this):
test[100][0] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
test[100][1] {
charge: "N",
mannum: "7",
canUse: "N"
}
How can I go about this so I can add more data into the object? I appreciate everyone's input for helping me find a resolution or even some knowledge.
Upvotes: 0
Views: 116
Reputation: 5074
If I understand well, you're trying to convert this into javascript:
PHP
$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
JAVASCRIPT
var array = {};
array['car'] = ['blue', 'green', 'purple'];
EXPLANATION
PHP associative arrays -> {} in JSON
PHP indexed arrays -> [] in JSON
UPDATE1
I'm expecting the results to be somewhat like this (It also doesn't have to look exactly like this):
test[100][0] = {
charge: "O",
mannum: "5",
canUse: "Y"
};
test[100][1] {
charge: "N",
mannum: "7",
canUse: "N"
}
Try this:
var test = {};
test[100] = [{"charge": "O", "mannum": "5", "canUse": "Y"}, {"charge": "N", "mannum": "7", "canUse": "N"}];
Upvotes: 0
Reputation: 816364
It seems like this is what you want:
test = {};
test[100] = [{ // test[100] is an array with a single element (an object)
charge: "O",
mannum: "5",
canUse: "Y"
}];
// add another object
test[100].push({
charge: "N",
mannum: "7",
canUse: "N"
});
Upvotes: 2