对json同属性字段压缩

function jsonPack(obj,ifOrder) {
    var result = []

    // var nameArr = Object.keys(obj[0]); 非有序遍历
    var nameArr = []
    var arr = JSON.stringify(obj[0]).replace(/^{|}$/g,'').split(',')
    nameArr = arr.map((item) => {
        return item.split(':')[0].replace(/"/g,'')
    })
    if (ifOrder == 1) {
        nameArr.sort()
    }
    result.push(nameArr)
    obj.forEach(item => {
        let tpmArr = []
        for (var i = 0; i < nameArr.length; i++) {
            tpmArr.push(item[nameArr[i]])
        }
        result.push(tpmArr)
    })
    console.log(result);
}


var obj = [{b:1,a:2,c:3},{a:1,b:2,c:3},{c:1,a:2,b:3}]
var abc = [{sha:1,hello:2,c:3},{hello:4,c:10,sha:2}]
jsonPack(obj)
jsonPack(abc)
posted @ 2019-04-03 20:11  樱风凛  阅读(344)  评论(0编辑  收藏  举报