[英]How to insert an object into an array which is inside an object?
Suppose if we are having data like this, how can we use dot notations or anything to update the array(data2) inside the object data1 which is inside the array(data).假设如果我们有这样的数据,我们如何使用点符号或任何东西来更新数组(数据)内的 object 数据 1 内的数组(数据 2)。
data = [
data1:
{
a:"1",
b:"2"
}
]
// another array(data2 - below) I am having I have to push that array inside
data1 as an object
data2 = [
{
c:"3"
},
{
d:"4"
}
]
The response I want as below:我想要的回复如下:
data = [
data1:
{
a:"1",
b:"2"
},
data2 = [
{
c:"3"
},
{
d:"4"
}
]
]
I didnt really understand your question but i think this is what you want?!我真的不明白你的问题,但我认为这就是你想要的?!
data = {
data1:
{
a: "1",
b: "2"
}
}
data2 = [
{
c: "3"
},
{
a: "3"
},
{
d: "4"
}
]
for (var key in data2) {
for (var key2 in data2[key]) {
if(data.data1[key2] != null){
console.log("data.data1 with they key" + key2 + " could have been replaced/updated with " + data2[key][key2]);
}
console.log("key " + key2 + " has value " + data2[key][key2]);
}
}
Result:结果:
key c has value 3 data.data1 with they keya could have been replaced/updated with 3 key a has value 3 key d has value 4键 c 具有值 3 data.data1 与它们 keya 可能已被替换/更新为 3 键 a 具有值 3 键 d 具有值 4
Edit:编辑:
Why dont you just do你为什么不做
data["data2"] = data2?
var array = [];
array['data1'] = { 'name': 'a' }
var array2 = [{ c: 3 }, { d: 4 }];
array['data2'] = array2;
console.log(array)
OutPut: OutPut:
[ data1: { name: 'a' }, data2: [ { c: 3 }, { d: 4 } ] ] [数据1:{名称:'a'},数据2:[{c:3},{d:4}]]
I tried on myself and I got the solution.我自己试了一下,我得到了解决方案。 If we have to make another field in an object you just give a name like this如果我们必须在 object 中创建另一个字段,您只需给出这样的名称
data.dataTwo
this will create another field with new name and now if we want to transfer or store an array in this we can simply do this这将创建另一个具有新名称的字段,现在如果我们想在其中传输或存储一个数组,我们可以简单地执行此操作
data.dataTwo = data2
This will assign that data2 named array in a new field what is given as dataTwo这将在一个新字段中分配名为 data2 的数组,该字段以 dataTwo 的形式给出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.