使一个(键值对)的值成为angular js中另一个的键

make value of one( key value pair )to be key of another in angular js

我有一个 json 响应,我想从中创建新的 json 对象

response = [
         {Detail:"Reuters ID",keyName:"Reuters_ID"},
         {Detail:"Parity One",keyName:"parity_one"},
         {Detail:"Parity level",keyName:"parity_level"}
        ];

我想在操作键值对后实现这个

lang_Arr =[
      {Reuters_ID:"Reuters ID"},
      {parity_one:"Parity One"},
      {parity_level:"Parity level"}
     ];

我试过两种方法 1) 在此获取错误作为意外的 tokken (.)

    var Lang_arr =[];
    angular.forEach(response, function(value, key) { 
     Lang_arr.push({value.keyName:value.Detail});

    });

2) 这里得到了意想不到的令牌[

 var Lang_arr =[];
    angular.forEach(response, function(value, key) { 
     Lang_arr.push({value['keyName']:value['Detail']});

    });

我也尝试过单独分配值,但它也不起作用

    var Lang_arr=[];
        var k ='';
        var v ='';
        var i = 1;

    angular.forEach(response, function(value, key) { 
        k ='';
        v ='';
        i = 1;
        angular.forEach(value,function(val,key){
            if(i == 1 )
                k = val;
            if(i == 2)
                v = val;

            if(!empty(k) && !empty(v))
                Lang_arr.push({k:v})



            i++;
        }); 

    });

您可以使用 javascript map 函数将对象映射到数组

var response = [
         {Detail:"Reuters ID",keyName:"Reuters_ID"},
         {Detail:"Parity One",keyName:"parity_one"},
         {Detail:"Parity level",keyName:"parity_level"}
];
        
var lang_Arr =[];

lang_Arr = response.map(function(o){
  var obj = {};
  obj[o.Detail] = o.keyName;
  return obj;
  
})

console.log(lang_Arr)

您必须在获得响应的 http 调用中分配它

$htpp.get(....).then(function(response){
lang_arr = []; 
 response.forEach(function(obj){
    var item = {obj.keyName : obj.detail};
    lang_arr.push(item);
}

用Angular forEach也可以实现这个功能

var response = [
         {Detail:"Reuters ID",keyName:"Reuters_ID"},
         {Detail:"Parity One",keyName:"parity_one"},
         {Detail:"Parity level",keyName:"parity_level"}
        ];
        var modifiedArray = [];
      angular.forEach(response, function(val, key) {
        var res = {};
            res[val.keyName] = val.Detail;
        this.push(res);
        }, modifiedArray);  

console.log(modifiedArray)

Working Example in Fiddle