本文主要是介绍JS拆分对象为键值对并转换为数组来回切换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这里我们使用 for... in 遍历
const data = {2: "笨笨",5: "小黑",3: "阿呆",};let newData = new Array;for (var i in data) {var json = {};if (data[i] != "") {json.id = i;json.name = data[i];newData.push(json);}}console.log(newData)// newData = [// {id:'2',name: "笨笨"},// {id:'5',name: "小黑"},// {id:'3',name: "阿呆"}// ];
打印:
将上面得到的数组转换为对象,这里使用了map数组遍历,如:
newData = [{id:'2',name: "笨笨"},{id:'5',name: "小黑"},{id:'3',name: "阿呆"}];let newArrs = new Object();newData.map((item) => {newArrs[item.id] = item.name;});console.log(newArrs)// const data = {// 2: "笨笨",// 5: "小黑",// 3: "阿呆",// };
打印:
这篇关于JS拆分对象为键值对并转换为数组来回切换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!