I have a JSON object that was returned from an XML to js function. This xml converter creates arrays for every entry even when they should be strings. I cannot modify this original function so therefore I would like to take my final json object, iterate through it, detect if a value is an array of length 1 and, if so, change that array to a string.
我有一个从XML返回到js函数的JSON对象。这个xml转换器为每个条目创建数组,即使它们应该是字符串。我无法修改此原始函数,因此我想获取我的最终json对象,遍历它,检测值是否为长度为1的数组,如果是,则将该数组更改为字符串。
Original object:
原始对象:
var json = {
user: {
name: ["bob"],
email: ["bob@example.org"]
},
items: [{
name: ["Object 1"]
},{
name: ["Object 2"]
}]
}
Should become:
应该成为:
var json = {
user: {
name: "bob",
email: "bob@example.org"
},
items: [{
name: "Object 1"
},{
name: "Object 2"
}]
}
I have considered the reviver function but a) I would like to avoid going back to a string and b) I am not sure if that would even work as it will probably just feed me each array element individually.
我已经考虑过reviver函数,但是a)我想避免回到字符串而b)我不确定这是否会起作用,因为它可能只是单独给我每个数组元素。
2 个解决方案
#1
2
This recursive function seems to work for this problem:
这个递归函数似乎适用于这个问题:
function simplify(obj) {
for (var k in obj) {
if (Object.prototype.toString.call(obj[k]) == '[object Array]' && obj[k].length == 1) {
obj[k] = obj[k][0];
}
else if (typeof obj[k] == 'object') {
obj[k] = simplify(obj[k]);
}
}
return obj;
}
simplify(json);
Demo: http://jsfiddle.net/xkz4W/
#2
2
Here's a recursive way to do it:
这是一种递归方式:
function flattenArrays(data) {
function processItem(item) {
if (Array.isArray(item)) {
if (item.length === 1 && typeof item[0] === "string") {
data[prop] = item[0];
} else {
for (var i = 0; i < item.length; i++) {
processItem(item[i]);
}
}
} else if (typeof item === "object") {
flattenArrays(item);
}
}
for (var prop in data) {
processItem(data[prop]);
}
}
Working demo: http://jsfiddle.net/jfriend00/L5WKs/
工作演示:http://jsfiddle.net/jfriend00/L5WKs/
#1
2
This recursive function seems to work for this problem:
这个递归函数似乎适用于这个问题:
function simplify(obj) {
for (var k in obj) {
if (Object.prototype.toString.call(obj[k]) == '[object Array]' && obj[k].length == 1) {
obj[k] = obj[k][0];
}
else if (typeof obj[k] == 'object') {
obj[k] = simplify(obj[k]);
}
}
return obj;
}
simplify(json);
Demo: http://jsfiddle.net/xkz4W/
#2
2
Here's a recursive way to do it:
这是一种递归方式:
function flattenArrays(data) {
function processItem(item) {
if (Array.isArray(item)) {
if (item.length === 1 && typeof item[0] === "string") {
data[prop] = item[0];
} else {
for (var i = 0; i < item.length; i++) {
processItem(item[i]);
}
}
} else if (typeof item === "object") {
flattenArrays(item);
}
}
for (var prop in data) {
processItem(data[prop]);
}
}
Working demo: http://jsfiddle.net/jfriend00/L5WKs/
工作演示:http://jsfiddle.net/jfriend00/L5WKs/