简体   繁体   English

如何将具有两对对象的对象添加到具有与对象相同的键和值的数组

[英]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.

相关问题 如何将具有两个键/值对的对象推入数组? - How to push an object with two key/value pairs into an array? 将数组排序为具有键和值对的对象,键和值对将相同值推入相同的键/值 - Sort array into an object with key and value pairs with same values being pushed into the same key/value 如果具有相同的键值,则将键值添加到对象数组 - Add key value to an object array if it has same key value 使用对象键值对的数组值将数组转换为对象 - Convert array to object using array values for object key value pairs 如何将对象中数组的索引值添加到键 - How to add index values of array in object to a key 如何比较两个对象数组,如果值相同,则添加新键:Javascript 中第二个对象的值 - How to compare two array of object and if value are same add new key: value on second object in Javascript 将计数值添加到具有相同键值的对象(对象数组的数组) - Add count value to object with same key values (array of array of objects) 如何将键值对添加到对象? - how to add key value pairs to object? 如何合并两个包含相同键的不同值的对象数组,并将新的 object 推入数组? - How to merge two array of objects containing different values of same key, and also push new object into the array? 如何将数组转换为 object 并在此 object Javascript 中添加相同的密钥? - How to convert array to object with add same key in this object Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM