How do I get only the value of an object?

How do I get only the value of an object?

Problem Description:

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?

Solution – 1

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

Solution – 2

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);

Solution – 3

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);
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject