Javascript 向对象添加元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14234646/
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
Adding elements to object
提问by HypeZ
I need to populate a json file, now I have something like this:
我需要填充一个 json 文件,现在我有这样的东西:
{"element":{"id":10,"quantity":1}}
And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.pushto add another element, I tried this:
我需要添加另一个“元素”。我的第一步是使用 将该 json 放入对象类型中cart = JSON.parse,现在我需要添加新元素。我想我必须cart.push用来添加另一个元素,我试过这个:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.
但是当我尝试这样做时element.push,我收到错误“对象没有方法推送” ,我认为我做的事情非常错误,因为我没有在任何地方告诉“元素”。
How can I do that?
我怎样才能做到这一点?
Edit:sorry to all I had a LOT of confusion in my head.
编辑:对不起,我脑子里有很多困惑。
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
我以为从 获取数据时只能获取对象类型JSON.parse,但我首先得到了放入 JSON 中的内容。
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!
用数组代替对象解决了我的问题,我在这里也使用了很多建议,谢谢大家!
回答by Konstantin Dinev
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
您的元素不是数组,但是您的购物车需要是一个数组才能支持许多元素对象。代码示例:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} }then perform:
如果您希望购物车成为表单中的对象数组,请{ element: { id: 10, quantity: 1} }执行:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify()was mentioned as a concern in the comment:
JSON.stringify()评论中提到了一个问题:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
回答by Sirko
With that row
随着那一行
var element = {};
you define elementto be a plain object. The native JavaScript object has no push()method. To add new items to a plain object use this syntax:
你定义element为一个普通对象。原生 JavaScript 对象没有push()方法。要将新项目添加到普通对象,请使用以下语法:
element[ yourKey ] = yourValue;
On the other hand you could define elementas an array using
另一方面,您可以element使用以下方法定义为数组
var element = [];
Then you can add elements using push().
然后您可以使用push().
回答by Craig MacGregor
If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:
如果购物车必须存储为对象而不是数组(尽管我建议存储为 []),您可以随时更改结构以使用 ID 作为键:
var element = { quantity: quantity };
cart[id] = element;
This allows you to add multiple items to the cart like so:
这允许您将多个项目添加到购物车,如下所示:
cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};
// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
回答by Melvin Chipimo
To append to an object use Object.assign
要附加到对象使用 Object.assign
var ElementList ={}
function addElement (ElementList, element) {
let newList = Object.assign(ElementList, element)
return newList
}
console.log(ElementList)
Output:
输出:
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
回答by Thakur Karthik
I was reading something related to this try if it is useful.
如果有用,我正在阅读与此尝试相关的内容。
1.Define a push function inside a object.
1.在对象内部定义一个push函数。
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
现在你可以像数组一样推送元素
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
这将产生这个对象
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push()function
注意元素添加了索引,并且还看到有一个新的长度属性添加到对象中。这对于查找对象的长度也很有用。这是因为push()函数的通用性质
回答by Cris
cart.push({"element":{ id: id, quantity: quantity }});
回答by shift66
you should write var element = [];
in javascript {}is an empty object and []is an empty array.
你应该var element = [];
在javascript中写{}是一个空对象并且[]是一个空数组。
回答by pashifika
function addValueInObject(object, key, value) {
var res = {};
var textObject = JSON.stringify(object);
if (textObject === '{}') {
res = JSON.parse('{"' + key + '":"' + value + '"}');
} else {
res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
}
return res;
}
this code is worked.
此代码有效。
回答by user3910831
Try this:
尝试这个:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
回答by Saad Patel
If anyone comes looking to create a similar JSON, just without using cartas an array, here goes:
如果有人想创建一个类似的 JSON,只是不使用cart数组,这里是:
I have an array of objects myArras:
我有一个对象数组myArr:
var myArr = [{resourceType:"myRT",
id: 1,
value:"ha"},
{resourceType:"myRT",
id: 2,
value:"he"},
{resourceType:"myRT",
id: 3,
value:"Li"}];
and I will attempt to create a JSON with the following structure:
我将尝试创建一个具有以下结构的 JSON:
{
"1":{"resourceType":"myRT","id":"1","value":"ha"},
"2":{"resourceType":"myRT","id":"2","value":"he"},
"3":{"resourceType":"myRT","id":"3","value":"Li"}
}
you can simply do-
你可以简单地做-
var cart = {};
myArr.map(function(myObj){
cart[myObj.id]= myObj;
});

