[英]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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.