Js在数组中添加元素

如何提取数组中的字段,然后添加新的字段,获取数据如下:


var data = [

{"id":"1","name":"华为","data":"25u6s8f545d3"},

{"id":"2","name":"小米","data":"cd58de9d3c5d"},

];

我想获得的数据格式如下:


var data = [

{"id":"1","name":"华为","data":"25u6s8f545d3","mac":"25:u6:s8:f5:45:d3"},

{"id":"2","name":"小米","data":"cd58de9d3c5d","mac":"cd:58:de:9d:3c:5d"},

];

我现在方法如下:


for (var i = 0; i < data.length; i++) {

    var mac = data[i].data.toUpperCase();

        mac1 = mac.substring(0, 2);

        mac2 = mac.substring(2, 4);

        mac3 = mac.substring(4, 6);

        mac4 = mac.substring(6, 8);

        mac5 = mac.substring(8, 10);

        mac6 = mac.substring(10, 12);

        var mac = mac1 + ':' + mac2 + ':' + mac3 + ':' + mac4 + ':' + mac5 + ':' + mac6;

        data[i].mac = mac;

 };

请教下有没有更好的方法?我觉得自己方法有点烂。


不负相思意
浏览 652回答 2
2回答

江户川乱折腾

var data = [&nbsp; { "id": "1", "name": "华为", "data": "25u6s8f545d3" },&nbsp; { "id": "2", "name": "小米", "data": "cd58de9d3c5d" },];data.forEach(item => {&nbsp; item.mac = item.data.replace(/\w{2}\B/g, '$&:')})console.log(data)

www说

var data = [&nbsp; { "id": "1", "name": "华为", "data": "25u6s8f545d3" },&nbsp; { "id": "2", "name": "小米", "data": "cd58de9d3c5d" },];var newData= data.map(item =>Object.assign({},item,{mac:item.data.match(/\w{1,2}/gi).join(":")}));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript