0

i have an array A

const arrayA = [
          {
            id:a,
            check:false
          },
          {
            id:b,
            check:false
          },
          {
            id:c,
            check:false
          } 

and an array B

const arrayB = [
  {
    id:a,
  },
  {
    id:b,  
  }
]

and i want to check if arrayB is exist arrayA by id, then change check to true. Using lodash or js array methods

5 Answers 5

4

Hopefully I understood your question correctly but this is the solution I came up with.

arrayA.map((item) => ({ ...item, check: arrayB.some(({ id: idB }) => item.id === idB ) }))
Sign up to request clarification or add additional context in comments.

Comments

2

You can use nested forEach loops, and check, if id matches then set check to true.

const arrayA = [{
    id: "a",
    check: false
  },
  {
    id: "b",
    check: false
  },
  {
    id: "c",
    check: false
  }
]

const arrayB = [{
    id: "a",
  },
  {
    id: "b",
  }
]

arrayB.forEach((b)=>{
  arrayA.forEach((a)=>{
   if(b.id == a.id){
    a.check = true;
   }
  })
})

console.log(arrayA);

Comments

0

You could create an array containing the ids of arrayB and then check the objects in arrayA like

const arrayA = [
          {
            id: 'a',
            check:false
          },
          {
            id:'b',
            check:false
          },
          {
            id:'c',
            check:false
          } ];
          
const arrayB = [
  {
    id:'a',
  },
  {
    id:'b',  
  }
];

const idsB = arrayB.map( obj => obj.id);
arrayA.forEach(obj => { if(idsB.indexOf(obj.id) > -1) obj.checked = true; } );
arrayA.forEach(obj => {console.log(JSON.stringify(obj))});

Comments

0

I could come up with this, which is not different than double loop, but may read easier.

arrayA.map((a) => {
    a.check = arrayB.findIndex((b) => b.id === a.id) != -1;
    return a;
});

Comments

0

Try this code it may help you

const arrayA = [
  {id:'a',check:false},
  {id:'b',check:false},
  {id:'c',check:false}
]
const arrayB = [
  {id:'a',},
  {id:'b',}
]

arrayB.map(i => {
   return i.check = arrayA.find(item => i.id == item.id)?.check;
});

console.log(arrayB)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.