JS 处理Json对象

有道JS题,如下:

https://img2.mukewang.com/5c7f2de500019e4301390181.jpg

要求:
Num的值在区间0~6之间,在json对象上加上键值对 'a':0;
Num的值在区间6~12之间,在json对象上加上键值对 'a':1;
Num的值在区间12~18之间,在json对象上加上键值对 'a':2;
Num的值在区间18~24之间,在json对象上加上键值对 'a':3;

结果这样:

https://img.mukewang.com/5c7f2dec00013ac101700176.jpg

因为最近大量做JS的数据处理,看了一些JS题,上网请教下其他朋友的思路和方法。谢谢

泛舟湖上清波郎朗
浏览 658回答 2
2回答

慕容3067478

这是,我个人觉得还是先对JSON进行遍历,针对不同的Num值,得到不同的a值,然后用字符串吧这些加起来,然后在调用JSON.parse()函数进行字符串到json的转换。我简单的写了个小函数,你可以参考下!!&nbsp; &nbsp; function jsonAdd(json) {&nbsp; &nbsp; &nbsp; &nbsp; var nArr=[];&nbsp; &nbsp; &nbsp; &nbsp; var ss='[';&nbsp; &nbsp; &nbsp; &nbsp; json.map((x)=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var num=parseInt(x.Num);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ss+='{"Num":'+num+","+'"a:":';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(num>0&&num<=6){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ss+='0},';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if(num>6&&num<=12){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ss+='1},';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if(num>12&&num<=18){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ss+='2},';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if(num>18&&num<=24){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ss+='3},';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; ss = ss.substring(0, ss.length - 1);&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ss+="]";&nbsp; &nbsp; &nbsp; &nbsp; return JSON.parse(ss);&nbsp; &nbsp; }调用函数,传入原始数据,返回一个修改后的数据.

慕的地10843

别人说Map一下没说错啊,另外json的属性名是双引号。拿走不谢var obj = json.map(function (t) {&nbsp; &nbsp; var val = +t['Num'];&nbsp; &nbsp; t['"a"'] = Math.floor(val/6).toString();&nbsp; &nbsp; return t;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript