【发布时间】:2016-11-22 10:42:00
【问题描述】:
我有两个数组
$scope.tags = [{ "id": 1, "name": "python" }, { "id": 2, "name": "NodeJs" }, { "id": 3, "name": "git" }]
另一个是
$scope.skillsInterested = [1,2];
想做什么?
如何映射上述数组并仅打印 id 的名称$scope.skillsInterested
我想在 第一个数组中打印名称,只有第二个存在的 id。
我在得到几个答案后尝试过这个
var tag_map = {};
for (var x = 0; x < $scope.tags.length; x++) {
tag_map[$scope.tags[x]['id']] = $scope.tags[x]['name'];
}
$scope.skillsInts = $scope.skillsInterested.map(function(x) {
return tag_map[x]
在运行 console.log
console.log("Result", tag_map);
有时会给出结果,有时会给出未定义的“地图”。
TypeError: Cannot read property 'map' of undefined
at controllers.js:141
at angular.js:16383
at m.$eval (angular.js:17682)
at m.$digest (angular.js:17495)
at m.$apply (angular.js:17790)
at l (angular.js:11831)
at J (angular.js:12033)
at XMLHttpRequest.t.onload (angular.js:11966)
提前致谢。
【问题讨论】:
-
告诉我们您的
forEach以及您遇到的错误 -
“仅打印”表示您要过滤第一个数组 - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
-
$scope.tags.filter(x=>x.id === $scope.selectedExpTags )[0].name或$scope.tags.find(x=>x.id === $scope.selectedExpTags ).name
标签: javascript angularjs arrays