简体   繁体   中英

How can I iterate (for key in obj) starting middle position

I have an obj:

let obj = {
    1: 'one',
    2: 'two',
    3: 'three',
    7: 'seven'
}

Is there an opportunity to iterate it starting 3 position, like this:

for (let key = 3 in obj) {
     console.log(obj[key]) // An output will be 'three' and 'seven'
}

I need to do this by the fastest way, because an obj is very huge

You can use the continue to skip the iteration if the key is less than 3 :

 let obj = { 1: 'one', 2: 'two', 3: 'three', 7: 'seven' }; for(let [key, val] of Object.entries(obj)){ if(key < 3 ){ continue; } console.log(val); } 

You can accomplish this in many ways. One algorithm would involve turning the object into an array. And then identifying the mid-point.

let obj = {
    1: 'one',
    2: 'two',
    3: 'three',
    7: 'seven'
}

Object.entries(obj).forEach(([key, value], index, array) => {
    const split = array.length/2
    const midPoint = split % 2 == 0 ? split : Math.floor(split)
    if(index >= midPoint){
        console.log(key)
    }
})

Just do it by a simple way.

let obj = {
  1: 'one',
  2: 'two',
  3: 'three',
  7: 'seven'
};

// make sure that your case is in order

// get keys of your object
const keys = Object.keys(obj);

// find index of starting key
const index = keys.indexOf('3');

// make sure index >= 0

// each all keys from starting key to the end by old school way
for (let i = index; i < keys.length; i++) {
  var key = keys[i];
  console.log(obj[key]);
}

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