rigisa
rigisa

Reputation: 13

How to iterate over a Map in batches in javascript?

I have this on a map. Could you please help how can I read this in a batch of 2 and call a process.

{
  ids: [
    {id: 1, value: 'abc'},
    {id: 2, value: 'abcd'},
    {id: 3, value: 'xyz'},
    {id: 4, value: 'foo'},
    {id: 5, value: 'bar'},
    {id: 6, value: 'blah'},
    {id: 7, value: 'blahblah'},
  ]
}

I tried the below one

let i = 0
let myNum = ids.length / 2
while (i < ids.length / myNum) {
   const searchString = ids
     .slice(myNum * i, myNum * (i + 1))
     .map(obj => {
       return `(id:${obj.id} AND value: ${obj.value})`
     })
     .join(' OR ')
   console.log(`${searchString}`)
   i++
}

output:

((id:1 AND value: abc) OR (id:2 AND value: abcd) OR (id:3 AND value: xyz))

((id:4 AND value: foo) OR (id:5 AND value: bar) OR (id:6 AND value: blah) OR (id:7 AND value: blahblah))

Upvotes: 0

Views: 1326

Answers (1)

rigisa
rigisa

Reputation: 13

this is working the way I wanted. Not sure if there is an efficient way of doing this. I am new to javascript.

let sliceValue = 2
let i = 0
while (i < ids.length) {
  const searchString = ids
    .slice(i, sliceValue + i)
    .map(obj => {
      return `(id:${obj.id} AND value: ${obj.value})`
   })
  .join(' OR ')

 console.log(`(${searchString})`)
 i = i + sliceValue
 }

output:

((id:1 AND value: abc) OR (id:2 AND value: abcd))
((id:3 AND value: xyz) OR (id:4 AND value: foo))
((id:5 AND value: bar) OR (id:6 AND value: blah))
((id:7 AND value: blahblah))

Upvotes: 0

Related Questions