[英]I am trying to push values from an object inside an array
I am trying to push data coming from an array of objects (key/value), then pushing it inside an array, to display them later. 我正在尝试推送来自对象(键/值)数组的数据,然后将其推送到数组中,以便稍后显示它们。
I have already tried doing the push inside the array but till now it is always giving undefined for the total amount of items being pushed. 我已经尝试过在数组内部进行推送,但到目前为止,对于推送的项目总数,它始终未定义。
//array
var clients_array = '[{"code": "1", "name": "client 1"},
{"code": "2", "name": "client 2"}, {"code": "3", "name": "client 3"}]';
var displayClient = [];
var json_parse1 = JSON.parse(clients_array);
json_parse1.forEach(function(client){
console.log(client.code + ' - ' + client.name);
displayClient.push(client.code + ' - ' + client.name);
alert(displayClient[i]);
})
Using the above code, In the console.log I am getting the correct data which I would like to push. 使用上面的代码,在console.log中,我获得了想要推送的正确数据。 But when alerting the displayClient array, which in this case should be filled with the console.logged data, it displays undefined for each data.
但是,当警告displayClient数组(在这种情况下应使用console.logged数据填充)时,它会为每个数据显示未定义。 Hence, I would like to push the correct data as displayed in the console.log.
因此,我想推送console.log中显示的正确数据。
You need to add a parameter for i
in the callback function. 您需要在回调函数中为
i
添加一个参数。
json_parse1.forEach(function (client, i) {
^
var clients_array = '[{"code": "1", "name": "client 1"}, {"code": "2", "name": "client 2"}, {"code": "3", "name": "client 3"}]'; var displayClient = []; var json_parse1 = JSON.parse(clients_array); json_parse1.forEach(function (client, i) { console.log(client.code + ' - ' + client.name); displayClient.push(client.code + ' - ' + client.name); alert(displayClient[i]); }) console.log(displayClient);
A better approach would be to use Array#map
and return the new items. 更好的方法是使用
Array#map
并返回新项目。
var array = [{ code: "1", name: "client 1" }, { code: "2", name: "client 2" }, { code: "3", name: "client 3" }], displayClient = array.map(({ code, name }) => [code, name].join(' - ')); console.log(displayClient);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.