user13849624
user13849624

Reputation:

iterate through an object from specific point

I want to iterate through the Cards object from specific point (const start) and find the first matching value of target then just break the loop and log a simple console log:

const Cards = {

    1: {
  val: "this is the value 1"
  },
  
  2: {
  val: "this is the value 2"
  },
  
  3: {
  val: "this is the value 3"
  },
  
  4: {
  val: "target"
  },
  
  5: {
  val: "this is the value 5"
  },
  
  6: {
  val: "this is the value 6"
  },
  
  7: {
  val: "target"
  },
  
}


const start = 2; // start searching the target from here

for (let [key, value] of Object.entries(Cards)) {
  // we start from 2 and in 4 we reach the first target so in 4 we should break the loop
  
     console.log(value.val)

}

Note: the keys in object are always 1,2,3,4...n

Upvotes: 0

Views: 64

Answers (2)

Coder365
Coder365

Reputation: 26

Another way:

const Cards = {
  1: { val: "this is the value 1" },
  2: { val: "this is the value 2" },
  3: { val: "this is the value 3" },
  4: { val: "target" },
  5: { val: "this is the value 5" },
  6: { val: "this is the value 6" },
  7: { val: "target" },
};

const start = 2 


for(i = 2; i <= Object.keys(Cards).length; i++){
     if(Cards[i].val === 'target'){
        console.log(`value found at ${i}`)
        return
     }
}

Upvotes: 0

Olian04
Olian04

Reputation: 6882

You can do it in a number of ways, this is how I would do it:

const Cards = {
  1: { val: "this is the value 1" },
  2: { val: "this is the value 2" },
  3: { val: "this is the value 3" },
  4: { val: "target" },
  5: { val: "this is the value 5" },
  6: { val: "this is the value 6" },
  7: { val: "target" },
};

// start searching the target from here
const start = 2;
const entries = Object.entries(Cards);

// we start from 2 and in 4 we reach the first target so in 4 we should break the loop
for (let i = start; i < entries.length; i++) {
  const [key, value] = entries[i];
  console.log(value.val);
}

Upvotes: 1

Related Questions