需求:有两个均是数组对象结构的数组,如下:
//第一个数组对象结构如下: arr1数组长度大于arr2
arr1=[
{adCode:"12340",adName:'河南省'},
{adCode:"12341",adName:'山东省'},
{adCode:"12342",adName:'广东省'},
{adCode:"12343",adName:'上海市'},
{adCode:"12344",adName:'安徽省'},
]
//第二个数组对象结构如下:
arr2=[
{adCode:'12342',adValue:"98"},
{adCode:'12340',adValue:"48"},
{adCode:'12341',adValue:"90"},
]
由上面的数据结构可以看出,若想获得如下数据结构:
arr3=[
{adName:"河南省",adValue:"48"}
]
则可进行如下操作:
const arr = arr1.map((v)=>{
const newResult = arr2.find((item)=>v.adCode ===item.adCode);
return {adName:v.adName,adValue:newResult.adValue}
})
若arr2数组结构如下:
arr2=[
{adCode:'12342',adValue:"98"},
{adCode:'12340',adValue:undefined},
{adCode:'12341',adValue:"90"},
{adCode:'12344',adValue:"40"},
{adCode:'12343',adValue:undefined},
]
则操作如下:
const arr = arr1.map((v)=>{
//adValue值为undefined时,不纳入新数组arr中
const newResult = arr2.find((item)=>v.adCode ===item.adCode) || {};
return {adName:v.adName,adValue:newResult.adValue}
})