[英]how to add an object with two pairs to an array that has a key and values that are same as the object
我需要基於服務器數據構建一個數組。 我將數據作為這樣的對象獲取:
{name: "test", hobby: "test"}
我要添加該對象的數組如下所示:
[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}]
輸出應為:
[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}, 2 : {name: "test", hobby: "test"}]
如何將元素添加到數組? 在這種情況下,推送不起作用。 我需要將鍵添加到元素,然后將其添加到數組的末尾,但我不知道如何。 請讓我知道有哪些選擇。謝謝。
如果要添加密鑰,則應使用對象。 喜歡
let obj = {};
function addData(){
let length = Object.keys(obj).length
temp = {name:"test"+(length+1),hobby:"test"+(length+1)}
obj[length]= temp;
console.log(obj);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.