gpt4 book ai didi

javascript - 从 angularjs 对象数组中获取值,它仅返回最后一项

转载 作者:行者123 更新时间:2023-12-03 02:47:05 25 4
gpt4 key购买 nike

我想使用 angular.forEach 从对象数组中获取值正是每个项目中元素的每个值。当我使用 angular.forEach 函数并循环对象数组时,它仅返回最后一项的值。我花了几个小时寻找和思考解决方案,但徒劳无功。

请查看我的代码:

这是我想要从中获取值的 json 文件中的对象数组。

数据.json:

[
{
"platform": "web-desktop",
"cdn": 4.3673292887e+10,
"p2p": 5.667683381e+09,
"total": 4.9340976268e+10,
"upload": 5.774321084e+09,
"percentage": 12,
"viewers": 1,
"maxViewers": 10,
"averageViewers": 1.5725853094274147,
"trafficPercentage": 69.49888073943228,
"live": "unknown"
},
{
"platform": "android",
"cdn": 1.7035777808e+10,
"p2p": 1.526916976e+09,
"total": 1.8562694784e+10,
"upload": 2.753179184e+09,
"percentage": 9,
"viewers": 1,
"maxViewers": 12,
"averageViewers": 1.416065911431514,
"trafficPercentage": 26.14635154335973,
"live": "unknown"
},
{
"platform": "ios",
"cdn": 2.994960132e+09,
"p2p": 9.6722616e+07,
"total": 3.091682748e+09,
"upload": 3.3788984e+07,
"percentage": 4,
"viewers": 1,
"maxViewers": 3,
"averageViewers": 1.152542372881356,
"trafficPercentage": 4.354767717207995,
"live": "unknown"
}
]

Controller .js:

'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);

function MainController ($scope, $http) {

var request = {
method: 'get',
url: 'data.json',
dataType: 'json',
contentType: "application/json"
};

$scope.arrData = new Array;
$http(request)
.then(function onSuccess(jsonData) {

// LOOP THROUGH DATA IN THE JSON FILE.
angular.forEach(jsonData.data, function (item) {

//Get data in each object
$scope.arrData = Object.keys(item).map(function(key){return item[key]});// get all values

});
console.log($scope.arrData);
});
}

结果如下:

["ios", 2994960132, 96722616, 3091682748, 33788984, 4, 1, 3, 1.152542372881356, 4.354767717207995, "unknown"]

或者,我想获得所有这些每一项。我应该在代码中添加什么才能使其正常工作!谢谢。

最佳答案

您将在 forEach 的每次迭代中覆盖 $scope.arrData

使用 map() 而不是 forEach() 并在外部 map() 回调中返回键映射

$scope.arrData = jsonData.data.map(function(item) { 
return Object.keys(item).map(function(key) {
return item[key]
});
});

关于javascript - 从 angularjs 对象数组中获取值,它仅返回最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48053841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com