我有两个对象,一个是回答一个问题而另一个是最终对象。喜欢
answer = {"value":"asda","indicator":"good"};
final = {} ;
我想将answer对象附加到最终对象,如此
final = {{"value":"asda","indicator":"good"},{"value":"sdad","indicator":"worse"}}
我该怎么做?
答案 0 :(得分:2)
您无法直接追加对象。相反,您需要将对象保存在数组中,如下所示。
answer = {"value":"asda","indicator":"good"};
final = [];
newObject = {"value":"sdad","indicator":"worse"};
现在您可以将对象推送到数组,如 -
final.push(answer);
final.push(newObject);
结果将是 -
final = [{"value":"asda","indicator":"good"},{"value":"sdad","indicator":"worse"}];
答案 1 :(得分:2)
var answer = {"value":"asda","indicator":"good"};
var final = [] //declare it as Array.
final = final.concat(answer);
更新回答:
使用 ecma6 ,可以使用spread operator
完成。
var answer = {"value":"asda","indicator":"good"};
final = {{"value":"sdad","indicator":"worse"}}
final = {...final,answer };//final as an object
OR
var answer = {"value":"asda","indicator":"good"};
final = {{"value":"sdad","indicator":"worse"}}
final = [...final,answer ]; //final as an array.
答案 2 :(得分:1)
为了将answer对象追加到final中,final必须是一个数组
var final =[];
final.push({"value":"asda","indicator":"good"})
or
final.push(answer);
答案 3 :(得分:1)
如果您使用ES2015,则可以
const answer = {"value":"asda","indicator":"good"};
const final = [].concat(Object.assign({}, answer))
或Ghazanfar'也有效