如何使用先前插入的项在同一数组索引处插入新数组值

时间:2014-04-12 07:57:48

标签: javascript jquery arrays

array push and splice提供了很多问题,但与此不一样。

请注意这个小提琴我尝试了什么 JS Fiddle

我有这样的输出

[{"rup":"100","dol":"50"},{"rup":"100","dol":"50"},{"expense":   
[{"reason":0,"cost":0,"receipt":0,"expense_type":0}]},{"expense":  
[{"reason":1,"cost":1,"receipt":1,"expense_type":1}]}]

但我需要的是

[{"rup":"100","dol":"50",{"expense":[{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50",{"expense":[{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]

我尝试了SPLICE() and ARRAY.INSERT()方法,但没有像上面那样。

请提出任何想法。

2 个答案:

答案 0 :(得分:4)

使用这段代码,

for (var i in costArray) {
    costArray[i].expense = expenseArray[i];
}

Out put:

[{"rup":"100","dol":"50","expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0}},
{"rup":"100","dol":"50","expense":{"reason":1,"cost":1,"receipt":1,"expense_type":1}}]

SEE THIS FIDDLE DEMO

答案 1 :(得分:1)

你想要的格式在javascript中无效,我想你的意思是:

{ "rup":"100","dol":"50", "expense":{"reason":0,"cost":0,"receipt":0,"expense_type":0} }

要解决此问题,请尝试替换

 costArray.push({"expense":expenseArray});

costArray[i]["expense"] = expenseArray

在第二个循环中。