Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript将元素添加到JSON对象中_Javascript_Arrays_Json - Fatal编程技术网

使用JavaScript将元素添加到JSON对象中

使用JavaScript将元素添加到JSON对象中,javascript,arrays,json,Javascript,Arrays,Json,我有一个JSON对象,例如: {result: [ { "id": "1", "name": "name 1" }, { "id": "2", "name": "name 2" }, { "id": "3", "name": "name 3" } ] } 我想知道如何将元素(例如:“user”:“username”)添加到

我有一个JSON对象,例如:

{result: 
   [ 
     { 
       "id": "1",
       "name": "name 1"
      },
      { 
       "id": "2",
       "name": "name 2"
      },
      { 
       "id": "3",
       "name": "name 3"
      }
  ]
}
我想知道如何将元素(例如:“user”:“username”)添加到这个JSON中的每个对象中,比如结果会是:

{result: 
   [ 
     { 
       "id": "1",
       "name": "name 1",
       "user": "user 1"
      },
      { 
       "id": "2",
       "name": "name 2",
       "user": "user 2"
      },
      { 
       "id": "3",
       "name": "name 3",
       "user": "user 3"
      }
  ]
}
我试着做一些事情,比如:

result.user = user.data 
但这并不是我所需要的。我想知道是否可以使用for循环,例如

for (var i = 0; i < result.length; i++) {
  result.user = user.data;
}
for(变量i=0;i
你很接近

for (var i = 0; i < result.length; i++) {
  // result.user = user.data;
  result[i].user = "user " + (i + 1);
}
for(变量i=0;i

本质上,结果是一组对象;在访问内部构件时,您需要告诉它要引用哪一个。

是使用数组索引。因为您希望第0个元素
1
,所以将1添加到索引中。 forEach将迭代每个数组元素。其中a是元素,索引是
a
th元素索引

var json={result:[{“id”:“1”,“name”:“name 1”},{“id”:“2”,“name”:“name 2”},{“id”:“3”,“name”:“name 3”}]};
json[“结果”].forEach(函数(a,索引){
a[“用户”]=“用户”+(索引+1);
})

log(json)首先需要将此json放入变量中,然后可以交互访问结果数组的对象

var对象={result:
[ 
{ 
“id”:“1”,
“名称”:“名称1”,
“用户”:“用户1”
},
{ 
“id”:“2”,
“名称”:“名称2”,
“用户”:“用户2”
},
{ 
“id”:“3”,
“名称”:“名称3”,
“用户”:“用户3”
}
]
};
for(var i=0;iconsole.log(对象)