简体   繁体   中英

how to add an object with two pairs to an array that has a key and values that are same as the object

I need to build an array based on server data. I get the data as an object like this:

{name: "test", hobby: "test"}

and my array that I want to add this object to looks like this:

[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}]

output should be:

[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}, 2 : {name: "test", hobby: "test"}]

How do I add the element to the array? Push did not work in this case. I need to add the key to the element and then add it to the end of array but I don't know how. Please let me know what are the options.Thanks.

if you want to add key, you should use object. like

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM