【js】json的相关操作

1、将json 数据和数组融合
demo

    <script>
        var json = {
            all: 10,
            un: 3,
            comp: 2,
            inc: 5

        }
        var arr = [
            {
                text: '全部',
                type: "",
            },
            { 
                text: '未参加', 
                type: "0", 
            },
            { 
                text: '未完成', 
                type: "1", 
            },
            { 
                text: '已完成', 
                type: "2", 
            },
        ];

        // 目标结果:
        arr = [
            { 
                text: '全部',
                type: "", 
                counts: 10
            },
            {
                text: '未参加', 
                type: "0", 
                counts: 3
            },
            { 
                text: '未完成', 
                type:  "1", 
                counts: 5
            },
            { 
                text: '已完成', 
                type: "2", 
                counts: 2
            },
        ];
        //实现  为arr 增加key值   
        var arr = [
            { 
                text: '全部', 
                type: "", 
                key: 'all' 
            },
            { 
                text: '未参加', 
                type: "0", 
                key: 'un' 
            },
            { 
                text: '未完成', 
                type: "1", 
                key: 'inc' 
            },
            { 
                text: '已完成', 
                type: "2", 
                key: 'comp' 
            }, 
        ];
        arr.forEach(item => {
            item.counts = json[item.key]
        });
        console.log(arr);
    </script>

2、将json 连接为 a=1&b=2

思路:先将json 变为数组 ['a=1','b=2']

然后再将数组变成字符串

var json2 = {
    a : 1,
    n : 5
}
let reloadPathHelper = (json) =>{
    return Object.keys(json).map(key => key + '=' + json[key]).join('&');
};
console.log(reloadPathHelper(json2));

方法二

var arr = [];
for(var key in json2){
    arr.push(key + '=' + json2[key]);
}
console.log(arr.join('&'));

 

posted on 2022-10-27 14:46  smile轉角  阅读(33)  评论(0编辑  收藏  举报

导航