我想问一个关于在android上将jsonArray转换为StringArray的问题。这是我获取jsonArray的代码
0:{Value: "0", Display: "w"}
1:{Value: "22", Display: "1w"}
2:{Value: "30", Display: "w2"}
3:{Value: "45", Display: "w3"}
我希望转换此格式
{"0":"w","22":"w2","30":"w2","45":"w3"}
这是我的代码
cols = [
{
Id: 'combo',
Values: [
{ "Value": "0", "Display": "w" },
{ "Value": "22","Display": "1w" },
{ "Value": "30", "Display": "w2" },
{ "Value": "45", "Display": "w3" }
],
},
]
var jsonString = JSON.stringify(cols.Values).replace("]", "").replace("[", "").replace("},{", "");
此结果
"{"Value":"0","Display":"w""Value":"22","Display":"1w"},
{"Value":"30","Display":"w2""Value":"45","Display":"w3"}"
答案 0 :(得分:0)
您可以迭代输入并创建所需的输出,如下所示: -
cols = [
{
Id: 'combo',
Values: [
{ "Value": "0", "Display": "w" },
{ "Value": "22","Display": "1w" },
{ "Value": "30","Display": "w2" },
{ "Value": "45","Display": "w3" }
],
},
];// this input is coming form somwhere
obj = {};
$.each(cols[0].Values,function(key,value){
obj[value.Value] = value.Display;
});
console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
注意: - “jQuery库必须为上述代码添加”。
或者您可以 只使用标准.forEach()
函数而不是$.each()
,然后此代码不需要jQuery。
.forEach()
示例: -
cols = [
{
Id: 'combo',
Values: [
{ "Value": "0", "Display": "w" },
{ "Value": "22","Display": "1w" },
{ "Value": "30","Display": "w2" },
{ "Value": "45","Display": "w3" }
],
},
];// this input is coming form somwhere
obj = {};
cols[0].Values.forEach(function(value) {
obj[value.Value] = value.Display;
});
console.log(obj);