-1

I use TypeScript. I want to get only the value of an object, but this error occurs: TypeError: Cannot read properties of undefined (reading 'cd1')”.

callList = {
  cd1: "00001",
  nm1: "17"
}

// cd = '17'
const getFindbyNm(cd) => {
  const idx = callList.find(e => e.nm1 == cd)

  console.log(idx['cd1']); // ← Error occuered.
}

What am I doing wrong?

tatsuya
  • 7
  • 4
  • Clearly, `callList` must be an Array, so please [edit] your post and provide a [mre]. How are you calling `getFindbyNm`? Did you forget to pass the argument for the parameter `cd`? Then it’s a duplicate of [Why is a global variable undefined inside a function when I call it?](/q/15309718/4642212). – Sebastian Simon Dec 05 '22 at 08:30
  • callList is not a list actually, possibly a typo ? A List of object will look like this `[{cd1: "00001", nm1: "17"}]` – No Name Dec 05 '22 at 08:35

3 Answers3

0

Considering callList is an Array

const callList =
  [{
    cd1: "00001",
    nm1: "17"
  }]

Array.prototype.find returns an array item or undefined, as an item may not be found within the given array. This is why idx may be undefined, hence cd1 may not exist on undefined

To fix it you can either check if idx isn't undefined

  if(idx){ 
    console.log(idx['cd1']);
  }

or use the optional chaining operator ?.

console.log(idx?.['cd1'])

TS Playground

Teneff
  • 30,564
  • 13
  • 72
  • 103
0

Your code isn't properly structured, it's not really valid JS even.

With some code cleaning, it works, but as some have stated, you need to use an Array for .find() to work.

const callList = {
  cd1: "00001",
  nm1: "17"
};

const cd = '17';
const getFindbyNm = (param1, param2) => {
  return param1.find(e => e.nm1 == param2);
};

console.log(getFindbyNm([callList], cd));
console.log(getFindbyNm([callList], cd).cd1);
Anuga
  • 2,619
  • 1
  • 18
  • 27
0

you can use Object.entries instead of find since find is function in array not in object. Object.entries has the attributes of both the key and the value

const callList = {
  cd1: "00001",
  nm1: "17",
};

const getFindByNm = (cd) => {
  let returnval;
  Object.entries(callList).forEach(([key, value]) => {
    if (key == 'nm1' && value == cd) {
      returnval = value;
    }
  });
  return returnval;
};

let val = getFindByNm("17");
console.log(val);
Stacks Queue
  • 848
  • 7
  • 18