猿问

js 重组数据

求助_(:3⌒゙)_
现在后台返回的数据是这样的:selected=['FREQUENT_PURCHASE','HIGH_CONSUME','NO_COMMUNICATE','DRIVE_RECORDER','SMART_LOCK','CHILD_MACHINE','FACE_RECS'];但是我想要的是
selectd={
userTag:['FREQUENT_PURCHASE','HIGH_CONSUME'],
communicationIntention:'NO_COMMUNICATE',
products:['DRIVE_RECORDER','SMART_LOCK','CHILD_MACHINE'],
cloudServices:['FACE_RECS'],
}
怎么根据下面的数据去重组??
data={
"CLOUD_SERVICE":[
{
"code":"CLOUD_STORE",
"msg":"云存储"
},
{
"code":"FACE_RECS",
"msg":"人脸识别"
},
{
"code":"WARN_CALL",
"msg":"电话报警"
},
{
"code":"HUMAN_CHECK",
"msg":"人形检测"
},
{
"code":"SERVICE_NEARLY_EXP",
"msg":"服务快到期"
}
],
"HAVE_PRODUCT":[
{
"code":"CAMERA",
"msg":"摄像机"
},
{
"code":"SMART_LOCK",
"msg":"xxxx"
},
{
"code":"CAT_EYE",
"msg":"xxxxx"
},
{
"code":"SUIT",
"msg":"套装"
},
{
"code":"SMART_CURTAIN",
"msg":"xxxx"
},
{
"code":"HW_VIDEO_RECORDER",
"msg":"硬盘录像机"
},
{
"code":"SENSE_WARN",
"msg":"传感报警"
},
{
"code":"CHILD_MACHINE",
"msg":"儿童机器人"
},
{
"code":"DRIVE_RECORDER",
"msg":"行车记录仪"
},
{
"code":"SPORT_CAMERA",
"msg":"运动相机"
},
{
"code":"NETWORK",
"msg":"网络通讯"
},
{
"code":"CAR_GOODS",
"msg":"汽车用品"
},
{
"code":"PARTS",
"msg":"配件"
},
{
"code":"SERVICE_PRODUCT",
"msg":"服务产品"
},
{
"code":"SAAS_APP",
"msg":"SaaS应用"
},
{
"code":"SMART_STORE",
"msg":"智能存储"
}
],
"USER_TAGS":[
{
"code":"FREQUENT_PURCHASE",
"msg":"购买频繁"
},
{
"code":"SMART_HOME_USER",
"msg":"xx家居用户"
},
{
"code":"MONITOR_USER",
"msg":"xx专业户"
},
{
"code":"NO_DEVICE",
"msg":"无设备用户"
},
{
"code":"INSTABLE_DEVICE",
"msg":"设备不稳定"
},
{
"code":"HIGH_ACTIVITY",
"msg":"活跃度高"
},
{
"code":"HIGH_CONSUME",
"msg":"高消费能力"
},
{
"code":"HOME_USER",
"msg":"家庭用户"
},
{
"code":"ENTERPRISE_USER",
"msg":"企业用户"
}
],
"COMMUNICATE_INTENTION":[
{
"code":"HAVE_INTENTION",
"msg":"有意向"
},
{
"code":"NO_COMMUNICATE",
"msg":"没有沟通过"
},
{
"code":"NON_INTENTION",
"msg":"无意向"
},
{
"code":"GET_DEAL",
"msg":"达成购买"
}
]
}
猛跑小猪
浏览 447回答 2
2回答

守着一只汪

像FREQUENT_PURCHASE这样的串,首先你要获取到它是data中的哪一类。可以遍历一遍data生成一个映射表typeMap:{CLOUD_STORE:'CLOUD_SERVICE',FACE_RECS:'CLOUD_SERVICE',CAMERA:'HAVE_PRODUCT',//...}你想要的selected,可以先初始化:lettargetSelected={userTag:[],communicationIntention:[],//...}这里有个小问题是targetSelected与data中的键不一致,但是一一对应,所以你要么写个函数,要么写个映射表,可以根据data中的key得到targetSelected中的key:functiongetKey(src){if(src=='CLOUD_SERVICE')return'cloudServices'//...}这样,对于后端返回的数组selected中的每一项,分发到targetSelected即可。selected.forEach(type=>{letkey=typeMap[type]targetSelected[getKey(src)].push(type)})其实很简单,但最好的方式后端直接返回规范的数据,如果实在不行再用上面的办法。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答