【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('&'));
作者:smile.轉角
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎关注我,一起进步!扫描下方二维码即可加我QQ
浙公网安备 33010602011771号