我有一个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++;
});
});
答案 0 :(得分:2)
您可以使用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)
答案 1 :(得分:1)
使用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)
答案 2 :(得分:0)
您必须在获得响应的http调用中分配
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}