如何把一个大的对象,转成若干个小对象,然后在放到数组中

我用了两种方法来解决它,一种较为复杂不提倡,一种较为简单

1.复杂的(不提倡)

    var obj = {A:1,B:2,C:3}
    var Barr = Object.entries(obj) //对象自身可枚举属性的键值对数组
    var  arr = []
    for (var i = 0; i < Barr.length; i++) {
        var  obj = {}  
        obj.num = i+1
        obj.title = Barr[i][0]
        obj.con = Barr[i][1]
        arr.push(obj)
    }

    console.log(arr)   //[ {num: 1, title: "A", con: 1},{num: 2, title: "B", con: 2},{num: 3, title: "C", con: 3}]  

2.简单方法(for ... in 遍历对象)

    var obj = { A: 1, B: 2, C: 3 }
    var arr = []; //创建一个数组
    for (var key in obj) { 
        var temp = {};   //创建临时对象
        temp.name = key;  //存储对象的Key为name
        temp.value = obj[key]; //存储value
        arr.push(temp);

    }
    console.log(arr)   //[ {num: 1, title: "A", con: 1},{num: 2, title: "B", con: 2},{num: 3, title: "C", con: 3}]  
posted @ 2019-11-22 11:40  SHY13  阅读(677)  评论(0编辑  收藏  举报