lastfor
lastfor

Reputation: 98

How can I check property in object with variable in loop Javascript

enter image description here

I'm trying to access object property, in a loop making variable to get a cell number from excel data.

but the problem is some has 'v' property in ws[cell], and error appears when it doesn't. error type is now TypeError, I think it's because it doesn't have 'v'. I have tried condition but error appears in same reason I guess. I want to resolve this. when there's no 'v' it just passes the loop otherwise it prints

I know I can use xlsx.utils.sheet_to_json to make it easier, but I want to know if I can solve this in JS.. please help out thanks in advance!

here's my code.

    const xlsx = require('xlsx');

let wb = xlsx.readFile('coupang_1.xlsx');

let sheetName = wb.SheetNames

let ws = wb.Sheets[sheetName[0]];
let refernceCell = ws[Object.keys(ws)[0]];
let range = refernceCell.substring(3,5);
let firstChr = range.charCodeAt(0);
let secondChr = range.charCodeAt(1);
let chr1 = '';
let chr2 = '';
let cellNum = firstObj.substring(5);
let limit = 90;
let cell = '';


for(let n=1; n<=cellNum; n++){
    for(let i=64 ; i<=firstChr; i++){
      chr1 = String.fromCharCode(i);
        if(i==firstChr){ 
          limit = secondChr;
        }else{
          limit = 90;
        }
        if(i==64){
          chr1 = '';
        }
        for(let j=65; j<=limit; j++){
          chr2 = String.fromCharCode(j);
          cell = chr1+chr2+n;
          let cellobj = ws[cell];
          console.log(cell);
          let b = 'v' in cellobj;
          (b)?console.log('got it'):console.log('nope');
  }
}
}
fraction of result
D2
got it
E2
C:\Users\q1\Documents\workspace\Practice\spread\sheet-to-json.js:57
          let b = 'v' in cellobj;
                      ^

TypeError: Cannot use 'in' operator to search for 'v' in undefined
    at Object.<anonymous> (C:\Users\q1\Documents\workspace\Practice\spread\sheet-to-json.js:57:23)

cell d2 doesn't have 'v' property.

Upvotes: 0

Views: 197

Answers (2)

Swaraj Gandhi
Swaraj Gandhi

Reputation: 714

As we can see from the error that cellobj is undefined. So to fix this issue, you put a condition around cellobj. Like

for (let j = 65; j <= limit; j++) {
  chr2 = String.fromCharCode(j);
  cell = chr1 + chr2 + n;
  let cellobj = ws[cell];
  if (cellobj) {
    let b = "v" in cellobj;
    b ? console.log("got it") : console.log("nope");
  }
}

Upvotes: 1

hackape
hackape

Reputation: 19957

As the error message currently shows, the problem is that cellobj is undefined, so you cannot apply the in operator to it.

I guess the real problem is in the cell = chr1+chr2+n line, you probably wanna console.log(cell) to check what really is spelled out as the cell number.

Good luck!

Upvotes: 1

Related Questions