skip to Main Content

Trying to compare next json key with the current.

my json object is as below

table_0: {
TR4TD1: ‘Regionnn’,
TR4TD2: ‘Actual Generation (MU) during May n’,
TR4TD5: ‘Actual Generation (MU) duringnApril to Maynn’,
TR5TD2: ‘2019n’,
TR5TD3: ‘2018n’,
TR5TD4: ‘% Growthn’,
TR5TD5: ‘2019n’,
TR5TD6: ‘2018n’,
TR5TD7: ‘% Growth’
}

I am trying using the

Object.entries(obj).forEach(key, value)=>{

// here i want to access current key and next key

//for e.g. current key ‘TR4TD2’, next key ‘TR4TD5’

})

2

Answers


  1. const jsonObject = {
      table_0: {
        TR4TD1: 'Regionnn',
        TR4TD2: 'Actual Generation (MU) during May n',
        TR4TD5: 'Actual Generation (MU) duringnApril to Maynn',
        TR5TD2: '2019n',
        TR5TD3: '2018n',
        TR5TD4: '% Growthn',
        TR5TD5: '2019n',
        TR5TD6: '2018n',
        TR5TD7: '% Growth'
      }
    };
    
    const keys = Object.keys(jsonObject.table_0);
    
    // Compare keys
    for (let i = 1; i < keys.length; i++) {
      if (keys[i] === keys[i - 1]) {
        console.log(`Key ${keys[i]} matches the previous key.`);
      } else {
        console.log(`Key ${keys[i]} does not match the previous key.`);
      }
    }
    

    use const keys = Object.keys(jsonObject.table_0); so that the statement return a set of keys then it is possible to iterate over the key and compare them too.

    Login or Signup to reply.
  2. I think you can access the next item in a object by doing this:

    let current = 0
    
    Object.entries(obj).forEach(key, value) => {
        const next = obj[key]
    
        // The current and next item are both accessible here
        // Note that the current item is 0 for the first key
    
    
        /* WRITE YOUR CODE HERE */
    
        current = obj[key]
    })
    

    What the code is doing is it’s actually finding the previous and current variables, but treating them as the current and next. Hope this works for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search