我有一个嵌套对象,如下所示(它可以有任意深度):
{
"a": 5,
"b": {
"0": 1,
"1": "x"
},
"x": {
"a": 1,
"1": "z"
},
"c": {
"0": 3,
"1": "Am",
"3":{
"0": 3,
"1": "x",
"2":{
"0": 3,
"1": "Y"
},
"length": 3
},
"length": 4
}
}
我必须将其转换如下(对象可能具有或不具有length属性):
{
"a": 5,
"x": {
"a": 1,
"1": "z"
},
"b": [1,"x"],
"c": [3, "Am",undefind, [ 3, "x", [ 3, "Y" ] ] ]
}
我写的方法如下:
function formatObjToArr(obj) {
var kys = Object.keys(obj);
var isObj = (/[^0-9]/g).test(kys.join('')) && !Array.isArray(obj);
if(!isObj){
obj.length===undefined && (obj.length = Math.max.apply(null,kys.map(function (i) { return parseInt(i) }))+1);
obj = Array.prototype.map.apply(obj,[function (i) { return i}]);
obj.forEach(function (i) {
(typeof i === "object" && i!==null) && formetObjToArr(i);
})
}else {
for (var property in obj) {
if (obj.hasOwnProperty(property) && property!=='length') {
if (typeof obj[property] === "object" && obj[property]!==null) {
formetObjToArr(obj[property]);
}
}
}
}
}
但是它只是添加了length属性,它没有改变类型。我的代码输出如下:
{
"a": 5,
"b": {
"0": 1,
"1": "x",
"length": 2
},
"x": {
"a": 1,
"1": "z"
},
"c": {
"0": 3,
"1": "Am",
"3": {
"0": 3,
"1": "x",
"2": {
"0": 3,
"1": "Y",
"length": 2
},
"length": 3
},
"length": 4
}
}
答案 0 :(得分:2)
var data = {
"a": 5,
"b": {
"0": 1,
"1": "x"
},
"c": {
"0": 3,
"1": "Am",
"length": 2
}
}
for(const d in data){
if(typeof data[d] === 'object'){
delete data[d]['length'];
data[d] = Object.values(data[d]);
}
}
console.log(data);
答案 1 :(得分:2)
您可以检查对象,并检查键是否在索引或length
的期望范围内,然后创建它的数组。此数组也应转换。
function convert(object) {
var keys;
if (!object || typeof object !== 'object') {
return object;
}
keys = Object.keys(object);
if (keys.every(k => k === 'length' || Math.floor(k) === +k && k >= 0 && k < Math.pow(2, 31))) {
return Object.assign([], object).map(convert);
}
return Object.assign(...keys.map(k => ({ [k]: convert(object[k]) })));
}
var data = { a: 5, b: { 0: 1, 1: "x" }, x: { 1: "z", a: 1 }, c: { 0: 3, 1: "Am", "3": { 0: 3, 1: "x", 2: { 0: 3, 1: "Y" }, length: 3 }, length: 4 } };
console.log(convert(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }