如何使用javascript批量迭代地图?

时间:2019-10-08 16:22:25

标签: loops dictionary literate-programming

我在地图上有这个。您能帮我如何以2批为单位阅读此书并调用流程。

{
  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'},
  ]
}

我尝试了以下一个

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++
}

输出:

((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))

1 个答案:

答案 0 :(得分:0)

这是我想要的方式。不知道是否有一种有效的方法。我是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
 }

输出:

((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))