You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确向对象存入键值对?AngularJS语言数据格式化问题

问题:如何将扁平化语言数据转为ID为键的对象结构?

我需要获取语言ID与语言文本的对应数据,当前使用的AngularJS代码如下:

for (var p in $scope.bulk.Langugaes) { 
  $scope.lsLanguagewithTextndValue.push($scope.bulk.Langugaes[p].Value, $scope.bulk.Langugaes[p].Text); 
}

执行后,lsLanguagewithTextndValue得到的是一个扁平化数组:

["1", "Marathi", "2", "English", "4", "Hindi", "3", "French"]

但我期望得到以语言ID为键、文本为值的对象结构,示例如下:

{
  "1": "Marathi",
  "2": "English",
  "3": "French",
  "4": "Hindi"
}

请问该如何修改代码实现需求?


解决方案

这很好改,核心就是把存储结构从数组换成对象,利用对象的键值对特性来实现你的需求~

方法一:修改原有的for...in循环

// 先把变量初始化为空对象,而不是数组
$scope.lsLanguagewithTextndValue = {};

for (var p in $scope.bulk.Langugaes) {
  // 直接用语言ID作为对象的键,文本作为对应的值
  $scope.lsLanguagewithTextndValue[$scope.bulk.Langugaes[p].Value] = $scope.bulk.Langugaes[p].Text;
}

方法二:使用AngularJS的angular.forEach(更推荐)

如果$scope.bulk.Langugaes是数组类型,用AngularJS内置的forEach会更符合框架风格,也能避免for...in可能带来的原型链遍历问题:

$scope.lsLanguagewithTextndValue = {};
angular.forEach($scope.bulk.Langugaes, function(language) {
  $scope.lsLanguagewithTextndValue[language.Value] = language.Text;
});

原理说明

原来的代码用push往数组里添加元素,自然会得到按顺序排列的扁平化数组;而我们现在把目标变量初始化为对象,每次循环时将语言ID作为键、文本作为值赋值给对象,就能直接得到你想要的键值对结构啦。

内容的提问来源于stack exchange,提问作者Ritesh Gore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:02:12