javascript 将匿名对象添加到对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6766817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add anonymous object to an object
提问by nkcmr
I know to add a named object to an existing JavaScript object you do this:
我知道要将命名对象添加到现有的 JavaScript 对象中,您可以这样做:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for()
statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
但是,如何以类似的方式将对象添加到现有的 JavaScript 对象中,而无需为其分配关联名称,以便可以通过for()
语句访问它。抱歉,如果我有点含糊,我对 JavaScript 对象了解不多。
UPDATE:
I want the end result to look like this:
更新:
我希望最终结果如下所示:
var json = [{name:'a'}{name:'b'}];
采纳答案by Tryster
Try an array that you push an item on to using
尝试将项目推送到使用的数组
myArrayVar.push(value);
or
或者
myArrayVar[myArrayVar.length] = value;
回答by Mrchief
What you have there is not strictly a JSON object. You're using JS object literals rather.
您所拥有的并不是严格意义上的 JSON 对象。您正在使用 JS 对象文字。
You can do this:
你可以这样做:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSONrepresentation of above will look like:
上面的JSON表示将如下所示:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
请注意,您不能拥有没有名称的属性。这是无效的:
// invalid, will throw error
jsObj = { : 'a'};
回答by Josh
What you are describing is an array of objects.
您所描述的是一组对象。
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
这具有您正在寻找的属性。你可以像这样操作它:
for(var i in j) {
alert(j[i].name);
}
回答by Pointy
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
拥有一个没有属性名称的对象的属性是没有意义的。毕竟,“for ... in”循环是对该属性名称集合的循环。那是,
for (var k in obj)
will set "k" equal to each of the namesof properties in "obj" in turn.
将依次设置“k”等于“obj”中的每个属性名称。
回答by Peter Porfy
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
您不能这样做,因为 JSON 对象是字符串值对的集合。值可以是数组,您可以将对象推入该数组,而无需关联名称。