undefinedfix
Sign in

How to generate new data structure for JS arrays

user3318674 edited in Tue, 03 Jan 2023

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

6 Replies
Sniper987
commented on Tue, 03 Jan 2023
 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}
        })
jjpr
commented on Tue, 03 Jan 2023

aaa.filter (item=>~ bbb.indexOf ( item.key )).forEach(item=> item.value=item.key )

larsankile
commented on Tue, 03 Jan 2023
const result = aaa.filter(item => bbb.includes(item.key)).map(item => {
    return {
        ...item,
        value: item.key
    };
})
Fastful
commented on Tue, 03 Jan 2023

aaa.reduce ((result, {key, label}) => bbb.includes (key) ? [... result, { value: key, label }] : result, [])

Wagner
commented on Wed, 04 Jan 2023

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
}, [])
blltt
commented on Wed, 04 Jan 2023

bbb.map (b=>{

let item = aaa.find(a=>a.key === b);
if(item) return {value: item.key, label: item.label};

}).filter(a => a !== undefined)