js 对象数组互相转换 数组转换为对象
JS 数组转对象 对象转数组 对象数组互相转换 数组对象互相转换
JS 数组转对象、对象转数组(针对嵌套深层次比较深的对象或者数组) JS
- 声明一个函数,arr_obj ,里面接收一个参数,参数类型只接受对象或者数组
- 如果没有传递任何参数 或者 传递的参数类型不符合要求,就会抛出错误异常
- 无论是没有传递参数 或者 传递的参数类型不符合要求,抛出异常 并 打印出传递的参数
- 如果要查看当前函数的对象,请通过 new 的方式实例化函数 arr_obj ,自行在控制台打印输出
- 调用此函数,传入数组会自动转换为对象;传入对象会自动转换为数组
// 数组转对象、对象转数组
function arr_obj(query) {
// 如果未传递参数,就赋值为 undefined
this.query = query || undefined;
this.params = this.query;
// 默认对象
var defaultObj = {
};
// 默认数组
var defaultArr = [];
// 数组转对象
this.arrToObj = function(arr) {
var obj = {
}
for (var i = 0; i < arr.length; i++) {
// 数组转为对象,对象的键=数组值, 对象的值=数组值
obj[arr[i]] = arr[i];
// 如果是数组,就再次调用自身 (this.arrToObj),递归接着循环
if (Object.prototype.toString.call(arr[i]) == "[object Array]") {
var deepArray = this.arrToObj(arr[i])
continue;
} else {
defaultObj[arr[i]] = arr[i]
}
}
this.params = defaultObj;
};
// 对象转数组
this.objToArr = function(obj) {
var arr = [];
for (var i in obj) {
arr.push(obj[i]);
// 如果是对象,就再次调用自身 (this.ObjToObj),递归接着循环
if(Object.prototype.toString.call(obj[i]) == "[object Object]"){
var deepObject=this.objToArr(obj[i]);
continue;
}else{
defaultArr.push(obj[i])
}
}
this.params = defaultArr;
};
if (Object.prototype.toString.call(this.query) == "[object Array]") {
this.arrToObj(this.query);
} else if (Object.prototype.toString.call(this.query) == "[object Object]") {
this.objToArr(this.query);
} else if (Object.prototype.toString.call(this.query) == "[object Undefined]") {
console.error("没有获取到传递进来的参数", this.params);
throw "没有获取到传递进来的参数"
} else {
console.error("错误的参数:", this.params,
"错误的参数类型:", Object.prototype.toString.call(this.params));
throw "传递的参数只能是对象或者数组类型"
}
return this.params;
}
// 调用 对象转数组
var obj = {
a1:"a",
b1:{
c1:"c",d1:"d"
,q1:{
q:"q",w:"w",
},
},
e1:"e",
f1:"f"
};
// // 调用 数组转对象
var arr = ["a", ["c",["e"],"q"],"t"];
var asd1 = new arr_obj(arr);
console.log(asd1);
// 输出 {a: "a", c: "c", e: "e", q: "q", t: "t"}
// 调用 对象转数组
var asd2=new arr_obj(obj);
console.log(asd2);
// 输出 ["a", "c", "d", "q", "w", "e", "f"]