Referring to the shuttle box of element, I set up two arrays
let aaa = [
{key:'0001',label:'图片1'},
{key:'0002',label:'图片2'},
{key:'0003',label:'图片3'},
{key:'0004',label:'图片4' },
{key:'0005',abel:'图片5'},
]
`let bbb = ['0001','0002','0003']`
Apply them to the selector of the element. According to the data selected in BBB, you want to convert the format to
[
{value:'0001',label:'图片1'},
{value:'0002',label:'图片2'},
{value:'0003',label:'图片3'},
]
I've thought about using map, but I don't know how to return the object that modifies the key value
aaa.forEach(item=>{
bbb.map(({key,label}) => {
if(item===key){
return {}
}
})
})
How to realize it
var result = aaa.filter((item)=>{
if(bbb.indexOf(item.key)!=-1){
return {value:item.key,label:item.lebel}
}
})
In addition, your map function is used in a wrong way. The parameter form is not correct I made a mistake about the usage of filter. Filter can only return the original data of array. The correct answer is as follows
var result = aaa.filter((item)=>{
return bbb.indexOf(item.key)!=-1
}).map((item)=>{
return {value:item.key,label:item.lebel}
})
aaa.filter (item=>~ bbb.indexOf ( item.key )).forEach(item=> item.value=item.key )
const result = aaa.filter(item => bbb.includes(item.key)).map(item => {
return {
...item,
value: item.key
};
})
aaa.reduce ((result, {key, label}) => bbb.includes (key) ? [... result, { value: key, label }] : result, [])
There are many ways to achieve it
aaa.reduce((acc, cur)=> {
if (bbb.includes(cur.key)) {
acc.push({ value: cur.key, label: cur.label })
}
return acc
}, [])
If code readability is not considered:
aaa.reduce((acc, { key:value, label }) =>{
if (bbb.includes(value)) {
acc.push({ value, label })
}
return acc
}, [])
bbb.map (b=>{
let item = aaa.find(a=>a.key === b);
if(item) return {value: item.key, label: item.label};
}).filter(a => a !== undefined)