简体   繁体   中英

Loop through 2 Arrays and assign a value from one array into each matching objects of second array

I have 2 Arrays 1.Options and 2.sameAccountArray

 options.map((opt, optInd) => {
            sameAccountArray.map((acObj, acInd) => {
                if (opt.optNumber === acObj.optNumber) {
                    console.log(opt.optNumber, acObj.optNumber, acObj.exist, acObj.exist, 'WTF', sameAccountArray);
                    opt.exist = acObj.exist;
                } else {
                    console.log(opt, acObj, opt.optNumber, acObj.optNumber, 'kundi');
                    // opt.exist = false;
                }
                // else {
                //     if (optInd === acInd) {
                //         opt.exist = acObj.exist;
                //     } else {
                //         console.log('elseeee', optInd, acInd,opt.optNumber, acObj.optNumber, opt.exist, acObj.exist);
                //     }
                // }
            });
        });

Data Structure of sameAccountArray:

{
                    'key': key,
                    'shares': this.no_of_shares[key],
                    'refValue': this.your_reference[key],
                    'exist': false,
                    'accountNumber': extractedAccountNumber, 'optNumber': parseInt(extractedOptionNumber)
                }

Option have big fields inside, but we don't need to care about it. options and sameAccountArray have common filed named optNumber . I am trying loop through each array and assign a value named exist in each object of the options array if optNumber is same. sameAccountArray already has the correct exist value, I just need to assign that value to match objects of options array. Somehow it's not assigned correctly. Please note that options array and sameAccount Array is not the same length. sameAccountArray has dynamic objects while options have a fixed number of elements. Any idea what is going wrong here guys? Thanks in advance

Try this:

options.forEach(opt=>{
    sameAccountArray.forEach(acObj=>{
      if (opt.optNumber === acObj.optNumber) opt.exist = acObj.exist;
    })
})

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

You cannot modify your arrays with map() function, but only create a new array with the results you want.

    let sameAccountObject={};

    sameAccountArray.forEach((account)=>{
        sameAccountObject[account.optNumber]=account;
    });

    let result=options.map((option)=>{
        let account=sameAccountObject[option.optNumber];
        if(account){
            option.exist=account.exist;
        }
       return option;
    });
 console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM