Javascript 添加到现有JSON“中”;“关键”;有价值

Javascript 添加到现有JSON“中”;“关键”;有价值,javascript,php,arrays,json,Javascript,Php,Arrays,Json,为了解释这一点,我正在创建一个JSON对象,并且使用这个对象,我希望能够像修改PHP数组一样修改它。这意味着我可以在任何给定的时间向数组中添加更多的值 例如,PHP如下所示: $array = array(); $array['car'][] = 'blue'; $array['car'][] = 'green'; $array['car'][] = 'purple'; test[100][0] = { charge: "O", mannum: "5", canUse: "Y" }

为了解释这一点,我正在创建一个JSON对象,并且使用这个对象,我希望能够像修改PHP数组一样修改它。这意味着我可以在任何给定的时间向数组中添加更多的值

例如,PHP如下所示:

$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
test[100][0] = {
  charge: "O",
  mannum: "5",
  canUse: "Y"
};
test[100][1] { 
  charge: "N",
  mannum: "7",
  canUse: "N"
}
可以看到,PHP可以使用“car”键向数组对象添加更多数据。我想对JSON对象做同样的事情,只是它可能并不总是作为键的字符串

function count(JSONObject) {
    return JSONObject.length;
}

test = {};
test[100] = {
  charge: "O",
  mannum: "5",
  canUse: "Y"
};
我知道你可以创建这样的新对象,但这不是我想要做的

test[101] = {
  charge: "O",
  mannum: "5",
  canUse: "Y"
};
这是我能想到的,但我知道它不起作用:

test[100][count(test[100])] { // Just a process to explain what my brain was thinking.
  charge: "N",
  mannum: "7",
  canUse: "N"
}
我希望结果会有点像这样(它也不必看起来像这样):


如何进行此操作,以便向对象中添加更多数据?感谢大家的帮助,帮助我找到解决方案,甚至一些知识。

如果我理解得很好,您正在尝试将其转换为javascript:

PHP

$array = array();
$array['car'][] = 'blue';
$array['car'][] = 'green';
$array['car'][] = 'purple';
JAVASCRIPT

var array = {};
array['car'] = ['blue', 'green', 'purple'];
解释

JSON中的PHP关联数组->{}

PHP索引数组->JSON格式的[]

更新1

我希望结果会有点像这样(事实也并非如此) 必须看起来像这样):

试试这个:

var test = {};
test[100] = [{"charge": "O", "mannum": "5", "canUse": "Y"}, {"charge": "N", "mannum": "7", "canUse": "N"}];

看起来这就是你想要的:

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

.

test.push({charge:'N',mannum:'7',canUse:'N'})
Whops,我不得不考虑一下。我修正了它来正确解释我的意思@阿迪内奥,这不只是一把新钥匙吗?示例到101,而不是100?或者你是说test[100].push()?我不确定你的意思,
javascript!=PHP
,javascript中没有关联数组,你不能像在其他语言中那样思考,你必须调整,而不是试图调整代码使其看起来像另一种语言。@adeneo这就是为什么我发布了一个示例,来解释我想弄明白的。我知道
Javascript
不是
PHP
。好吧,那么
test[100]
必须是一个数组,你只需调用
。push
。我不想把PHP数组转换成Javascript。另外,最好用json_encode($array);.^uz~来回答这个问题。不要将JavaScript中的对象文字与JSON混淆。您根本没有发布任何JSON。感谢您的贡献!然而,我在任何时候都不会有关于我的数据,因为这些信息来自数据库。所以我需要一个动态的方法。
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"
});