我有一个JSON数组对象,格式如下
{"Object1":[
{"field1":"label1", "field2":"Name1"},
{"field1":"label2", "field2":"Name2"},
{"field1":"label3", "field2":"Name3"}
]}
我想将其转换为
{"label1":"Name1", "label2":"Name2", "label3":"Name3"}
我如何实现这一目标?
答案 0 :(得分:1)
创建一个空对象,然后遍历Object1
对象,对于其中的每个对象,将field1
中的键添加到空数组中,其值为field2
。
类似的东西:
var _obj = {};
jQuery.each(obj.Object1, function(k, v) {
_obj[v.field1] = v.field2;
});
答案 1 :(得分:1)
为实现这一目标 这对你有用
//将此分配给任何变量
var obj={"Object1":[
{"field1":"label1", "field2":"Name1"},
{"field1":"label2", "field2":"Name2"},
{"field1":"label3", "field2":"Name3"}
]};
//Now take an array
try{
var arr=obj.Object1;
var newObj={};
for(var i=0;i<arr.length;i++)
{
newObj[arr[i].field1]=arr[i].field2;
}
alert(JSON.stringify(newObj));
}
catch(err){alert(err.message);
}
答案 2 :(得分:0)
使用基本for loop
的纯JS中的某些内容:http://jsfiddle.net/1c911ebr/
var object = {"Object1":[
{"field1":"label1", "field2":"Name1"},
{"field1":"label2", "field2":"Name2"},
{"field1":"label3", "field2":"Name3"}
]},
content = object["Object1"],
newObj = {};
for(var i=0; i<content.length; i++){
newObj[content[i].field1] = content[i].field2;
}
将返回:
{label1: "Name1", label2: "Name2", label3: "Name3"}
答案 3 :(得分:0)
var json = {"Object1":[
{"field1":"label1", "field2":"Name1"},
{"field1":"label2", "field2":"Name2"},
{"field1":"label3", "field2":"Name3"}
]};
function getJSONObj()
{
var gList = eval("(" + json + ")");
var jsonObj = {};
$.each(gList.Object1, function (keyData, valueData)
{
jsonObj[valueData.field1] = valueData.field2;
});
}
getJSONObj();
输出:
{"label1":"Name1", "label2":"Name2", "label3":"Name3"}
答案 4 :(得分:-1)
尝试,基于纯JavaScript的解决方案。
var gList= {"Object1":[
{"field1":"label1", "field2":"Name1"},
{"field1":"label2", "field2":"Name2"},
{"field1":"label3", "field2":"Name3"}
]};
function transform(){
var arr = [];
for(var i=0;i<gList.Object1.length;i++){
arr.push("'" + gList.Object1[i].field1 + "':'" + gList.Object1[i].field2 + "'");
}
alert(arr);
}
<强>输出强>
'label1':'Name1','label2':'Name2','label3':'Name3
答案 5 :(得分:-1)
使用此代码。
var json = "{'Object1':["+
"{'field1':'label1', 'field2':'Name1'},"+
"{'field1':'label2', 'field2':'Name2'},"+
"{'field1':'label3', 'field2':'Name3'}"+
"]}";
function getJSONObj(){
var gList = eval("(" + json + ")");
var jsonObj = {};
for(var i=0;i<gList.Object1.length;i++){
jsonObj[gList.Object1[i].field1 ] = gList.Object1[i].field2;
}
alert(JSON.stringify(jsonObj));
}
getJSONObj();