Javascript如何在循环中向对象添加新对象

时间:2016-01-27 14:19:17

标签: javascript arrays object

我需要创建像这样的对象数组

var vegetables = "babana": {"store": store, "foo": foo}, "tomato": {"store": store, "foo": foo}, "orange": {"store": store, "foo": foo};

我从循环和循环中获取所有数据,如下所示:

for(var v in vegetablesData) {
    // this code dosent work with "=" its only adding the last entry from the array
   // the data of the 'store' and 'foo' are taken from somewhere other place from the code, i didnt wrote from where, because im thinking that is it irrelevant to my question
    test[vegetables[v]] = {"store": store, "foo": foo};
}

我需要它的输出应采用这种格式(使用JSON.stringify(vegetables)):

{"vegetables": {"babana": {"store": store, "foo": foo}, {"tomato": {"store": store, "foo": foo}, "orange": {"store": store, "foo": foo}}

我与

联系在一起
  

.push

但它不起作用。我用+ =尝试了,但仍然有效。我是菜鸟,所以我需要你的帮助。谢谢!

2 个答案:

答案 0 :(得分:3)

在您的示例中,您没有处理数组。

如果实际上迭代对象的键,则使用for语法。如果要将对象添加到对象,只需使用键和这样的值。

obj[key] = value

在您的示例中,您将vegetable的内容设置为键v作为对象`test的键。

for(var v in vegetablesData) {
    test[v] = {"store": store, "foo": foo};
}

在测试中你的确不清楚,但你最终可能会做这样的事情:

 test['vegetables'] = {}
 for(var v in vegetablesData) {
     test['vegetables'][v] = {"store": store, "foo": foo};
 }

答案 1 :(得分:-1)

Nested JSON: How to add (push) new items to an object?

上面的示例是这样的:

library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};

正如评论中所说,你将对象视为一个数组,它不是一个数组,所以.push不会工作所以你必须像上面那样设置它。

您也没有在对象中使用正确的元素。所以而不是:

for(var v in vegetablesData) {
    // this code dosent work with "=" its only adding the last entry from the array
   // the data of the 'store' and 'foo' are taken from somewhere other place from the code, i didnt wrote from where, because im thinking that is it irrelevant to my question
    test[vegerables[v]] = {"store": store, "foo": foo};
}

使用此:

for(var veg in vegetablesData) {
    // this code dosent work with "=" its only adding the last entry from the array
   // the data of the 'store' and 'foo' are taken from somewhere other place from the code, i didnt wrote from where, because im thinking that is it irrelevant to my question
    test[veg] = {"store": store, "foo": foo};
}