我正在转换一些数据,以便以可读的方式将其发送到前端。
我只是将一些XML数据转换为JSON,我得到一个对象,但每个值都是key : ['value']
,我需要它key: 'value'
我发送的数据如res.status(200).json({dealersData});
dealersData
返回此
{
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
所以你可以看到我收到数据"TypeId":["1"]
等等,我不想这样,我想要"TypeId" : 1
,那么我应该怎么做才能将这些数组转换为对象希望使用Lodash
?
答案 0 :(得分:3)
这将以递归方式逐步遍历对象,将长度为1的数组更改为字符串:
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
function process(obj) {
for(var key in obj) {
if(obj[key] instanceof Array && obj[key].length==1) {
obj[key]= obj[key][0];
}
else if(obj[key] instanceof Object) {
process(obj[key]);
}
}
} //process
var obj= {
"dealersData": [
{
"DealerId": [
"1"
],
"DealerName": [
"Carmen"
],
"NickName": [
"Carmen"
],
"Picture": [
"00001.jpg"
],
"Active": [
"1"
],
"LegalId": [
"111111111"
],
"TypeId": [
"1"
]
},
{
"DealerId": [
"14"
],
"DealerName": [
"Jaz"
],
"NickName": [
"Jaz"
],
"Active": [
"1"
],
"LegalId": [
"111111187"
],
"TypeId": [
"1"
]
}
]
}
process(obj);
document.querySelector('pre').innerHTML= JSON.stringify(obj,'\n',2);
<pre></pre>
答案 1 :(得分:3)
对于每个经销商迭代密钥并将值替换为值[0]。
dealersData = dealersData.map( function( dealer ){
Object.keys( dealer ).forEach( function(key){
dealer[key] = dealer[key][0];
})
return dealer;
});
http://jsfiddle.net/r38u4qag/1/(或ES2015胖箭版:http://jsfiddle.net/r38u4qag/2/)
答案 2 :(得分:1)
如果我做对了,你就有阵列,但是你不需要它们,因为你总是只返回一个值,对吗?
如果是这种情况,您只需要在数组对象上调用.toString()
方法。我会迭代你的 dealersData 来在所有阵列上执行此操作:
for(var i = 0; i < dealersData.length; i++) {
dealersData[i].DealerId = dealersData[i].DealerId.toString();
dealersData[i].DealerName = dealersData[i].DealerName.toString();
[...]
}