js将数组转化为一个对象obj,将数组中的内容作为对象的key转化为对象,将数组中的某项内容作为分类来转成对象
程序员文章站
2022-04-24 21:56:44
...
1.js数组转成对象
var list = {};
var arr = ["123","456","789"];
// for in 循环
for (var key in arr) {
list[key] = arr[key];
}
console.log(list); //控制台打印
打印如下
我的思路就是这样,不止这一种其他循环也可以forEach、map、reduce等等
2.将数组中的内容作为对象的key转化为对象
//数组
var formArr = [
{name: "张三", num: "1"},
{name: "李四", num: "2"},
{name: "王二", num: "3"},
{name: "麻子", num: "4"}
];
//创建对象
var obj={ };
//map循环方式
formArr.map(function (e, item) {
obj[e.num] = e.name;
});
console.log(obj); //控制台打印
结果打印:obj = {1: “张三”, 2: “李四”, 3: “王二”, 4: “麻子”}
不止这一种其他循环也可以forEach、for in、reduce等等
3.将数组中的某项内容作为分类来转成对象
例如页面上有个小组(group)成员,点击那个小组显示那个小组的成员
//数组
var formArr = [
{name: "张三", group: "1"},
{name: "李四", group: "1"},
{name: "王二", group: "2"},
{name: "麻子", group: "2"},
{name: "小明", group: "3"},
{name: "小红", group: "3"},
{name: "隔壁", group: "4"},
{name: "老王", group: "4"}
];
//创建对象
let obj = {}
//forEach循环
formArr.forEach(item => {
if (!obj[item.group]) {
obj[item.group] = [item]
} else {
obj[item.group].push(item)
}
})
console.log(obj) //控制台打印
结果打印:
展开
然后在页面上循环展示即可