Home > Mobile >  Storing both found and not found array
Storing both found and not found array

Time:06-07

i have two array below as below:

mainArray = [
{id:1, name: 'one'},
{id:2, name: 'two'},
{id:3, name: 'three'},
{id:4, name: 'four'},
{id:5, name: 'five'}
]

newArray = [
{id:1, isChecked = 1},
{id:2, isChecked = 1}
]

I am stroing the matched and unmatched information in my postgres table: table structure

 ________________ 
|id  | isChecked |
 ----------------
| 1 |   1       |
| 2 |   1       |
| 3 |   0       |
| 4 |   0       |
| 5 |   0       |
-----------------

I am first searching if the ID of newArray is matched in mainArray then store in the table with isChecked = 1 otherwise also stroing id's those not matched in mainArray with isChecked = 0;

I have writted this logic:

for (i=0;i<mainArray.length;i  ){
    if(mainArray[i].id == newArray[i].id){
        insert into mytable values (mainArray[i].id, 1);
    }else {
        insert into mytable values ( mainArray[i].id, 0);
    }

}

But this not storing the unmatched info only storing matched info.

CodePudding user response:

var mainArray = [
{id:1, name: 'one'},
{id:2, name: 'two'},
{id:3, name: 'three'},
{id:4, name: 'four'},
{id:5, name: 'five'}
];
var newArray = [
{id:1, isChecked:1},
{id:2, isChecked: 1}
];
var a = [];
mainArray.forEach((main) => {
    var exists = newArray.find((x) => x.id === main.id)
    if(exists){a.push({id: main.id, isChecked: 1})}
    else{a.push({id: main.id, isChecked: 0})}
});
console.log(a)

CodePudding user response:

You can try it with some() for checking isChecked or find() for getting isChecked record

const mainArray = [
  {id:1, name: 'one'},
  {id:2, name: 'two'},
  {id:3, name: 'three'},
  {id:4, name: 'four'},
  {id:5, name: 'five'}
]
const newArray = [
  {id:1, isChecked:1},
  {id:2, isChecked: 1}
]
mainArray.forEach(obj => {
  let isChecked = newArray.some(ele => obj.id === ele.id && ele.isChecked)
  if(isChecked) {
    //insert into mytable values (obj.id, 1)
  } else {
    //insert into mytable values (obj.id, 0)
  }
})

// for get array
const arrInsert = mainArray.map(obj => {
  let other = newArray.find(ele => obj.id === ele.id && ele.isChecked)
  return {id : obj.id, isChecked : (other ? other.isChecked : 0)}
})
console.log(arrInsert)

  • Related