[英]How to add multiple Objects into an Array inside an Object
我下面的代碼會將最后生成的對象添加到 Person 對象的phones 數組中。 我想要做的是能夠將所有生成的對象添加到phones 數組中。
var person = {
username : username,
phones : []
}
// Added Profile
var phoneObjs = {};
var addedPhones = $('.added_phone');
循環遍歷所有新 . added_phone 輸入值的函數:
addedPhones.each( function(i) {
var tag = $(this).children("label").text();
var value = $(this).children("input").val();
phoneObjs = $(this).map(function(i,el) {
var $el = $(el);
return {
tag: tag,
label: value
}
}).get();
console.log(phoneObjs);
person.phones = phoneObjs;
// person.phones.push(phoneObjs);
console.log(person.phones);
});
我將創建 2 個新的輸入字段並輸入 2 個不同的數字,接下來我提交表單並運行上面的函數。 從 chrome 控制台console.log(person.phones)
:
第二次循環時,第一個對象被替換
你會如何避免這個問題?
在 ES5 中
person.phones = person.phones.concat(phoneObjs);
在 ES6 中:
person.phones = [...person.phones,...phoneObjs];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.