当前位置:网站首页>How to convert an array to an object, and how to convert an object to an array
How to convert an array to an object, and how to convert an object to an array
2022-06-24 10:37:00 【Yansuizi blog】
Catalog
One 、 How to convert an array to an object
3、 ... and 、 Mutual conversion is encapsulated into functions
One 、 How to convert an array to an object
1、 demand
let arr = [{label: ' male ', value: 0},{label: ' Woman ', value: 1}]
// Convert to
let obj = {0:' male ', 1:' Woman '}
2、 Realization
Train of thought :
- array-based forEach Method traverses the array
- Define an empty object
- Will iterate through each of the resulting objects value Be worthy of being a new object key,label As the value of the new object
- At the end of the cycle obj The value of is returned to the caller
let arr = [{label: ' male ', value: 0},{label: ' Woman ', value: 1}]
function arrToObj(arr){
let obj = {}
arr.forEach(item => {
obj[item.value] = item.label
})
return obj
}
const obj1 = arrToObj(arr)
console.log(' Array forEach Method ', obj1)
Train of thought two :
- array-based forEach Method traverses the array
- Define an empty object
- Will iterate through each of the resulting objects value Be worthy of being a new object key,label As the value of the new object
- At the end of the cycle obj The value of is returned to the caller
let arr = [{label: ' male ', value: 0},{label: ' Woman ', value: 1}]
function arrToObj1(arr){
return arr.reduce((obj,item) => {
obj[item.value] = item.label
return obj
},{})
}
const obj2 = arrToObj1(arr)
console.log(' Array reduce Method ', obj2)
Two 、 Object to array
1. demand
let obj = { 0: ' male ', 1: ' Woman ' }
// Convert to
let arr = [{label: ' male ', value: 0},{label: ' Woman ', value: 1}]
2. Realization
let obj = { 0: ' male ', 1: ' Woman ' }
// Use for...in... loop , Get the key of the object 、 value
// Make it a new object , array-based push Method is appended to the array
function objToArr(obj){
let arr = []
for(let key in obj){
arr.push({
label: obj[key],
value: key
})
}
return arr
}
const arr = objToArr(obj)
console.log(arr)
3、 ... and 、 Mutual conversion is encapsulated into functions
// Array to object 、 Object to array
function arr_obj(query) {
// If the parameter is not passed , It is assigned as undefined
this.query = query || undefined;
this.params = this.query;
// Default object
var defaultObj = {};
// The default array
var defaultArr = [];
// Array to object
this.arrToObj = function(arr) {
var obj = {}
for (var i = 0; i < arr.length; i++) {
// Array to object , Object's key = Array value , The value of the object = Array value
obj[arr[i]] = arr[i];
// If it's an array , Call itself again (this.arrToObj), Recursion followed by loop
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;
};
// Object to array
this.objToArr = function(obj) {
var arr = [];
for (var i in obj) {
arr.push(obj[i]);
// If it's an object , Call itself again (this.ObjToObj), Recursion followed by loop
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(" The parameter passed in was not obtained ", this.params);
throw " The parameter passed in was not obtained "
} else {
console.error(" Wrong parameters :", this.params,
" Wrong parameter type :", Object.prototype.toString.call(this.params));
throw " The parameters passed can only be object or array types "
}
return this.params;
}
// call Object to array
var obj = {
a1:"a",
b1:{
c1:"c",d1:"d"
,q1:{
q:"q",w:"w",
},
},
e1:"e",
f1:"f"
};
// // call Array to object
var arr = ["a", ["c",["e"],"q"],"t"];
var asd1 = new arr_obj(arr);
console.log(asd1);
// Output {a: "a", c: "c", e: "e", q: "q", t: "t"}
// call Object to array
var asd2=new arr_obj(obj);
console.log(asd2);
// Output ["a", "c", "d", "q", "w", "e", "f"]
边栏推荐
- Resolved: methods with the same name as their class will not be constructors in
- Appium自动化测试基础 — 移动端测试环境搭建(一)
- Wechat applet rich text picture width height adaptive method introduction (rich text)
- 126. 单词接龙 II BFS
- Caching mechanism for wrapper types
- leetCode-223: 矩形面积
- Leetcode-1089: replication zero
- Uniapp develops a wechat applet to display the map function, and click it to open Gaode or Tencent map.
- Flink checkPoint和SavePoint
- Multithreaded applications - improve efficiency
猜你喜欢

26.删除有序数组的重复项
![[data analysis data source] coordinates of provinces, cities and administrative regions across the country (including boundary coordinate points and central coordinate points)](/img/a8/84088b1e61deaf62f22d85a007423b.png)
[data analysis data source] coordinates of provinces, cities and administrative regions across the country (including boundary coordinate points and central coordinate points)

How can I solve the problem that the swiper animation animation fails when switching between left and right rotations of the swiper?

leetCode-223: 矩形面积

【IEEE出版】2022年自然语言处理与信息检索国际会议(ECNLPIR 2022)

JMeter接口测试工具基础— 使用Badboy录制JMeter脚本

Petit guide de construction rapide du bras mécanique (II): application du bras mécanique

Thread operation principle

Leetcode-2221: triangular sum of arrays

分布式系统你必须了解的点-CAP
随机推荐
3.员工的增删改查
Leetcode-2221: triangular sum of arrays
leetCode-2221: 数组的三角和
牛客-TOP101-BM29
Uniapp implementation forbids video drag fast forward
【IEEE出版】2022年智能交通与未来出行国际会议(CSTFM 2022)
HBuilder制作英雄皮肤抽奖小游戏
Thread pool execution process
多线程的应用 - 提升效率
百度网盘下载一直请求中问题解决
2022 International Symposium on intelligent robots and systems (isoirs 2022)
Web project deployment
機械臂速成小指南(二):機械臂的應用
包装类型与基本类型的区别
[resource sharing] 2022 International Conference on Environmental Engineering and Biotechnology (coeeb 2022)
Leetcode-223: rectangular area
JMeter interface test tool foundation - badboy tool
Resolved: methods with the same name as their class will not be constructors in
Sort out interface performance optimization skills and kill slow code
Appium automation test foundation - mobile end test environment construction (I)