javascript - How to safe get value from object (return null when not exist) - Stack Overflow

I want to lookup for a key on an object, but if the key does't exist, it must return null, is it p

I want to lookup for a key on an object, but if the key does't exist, it must return null, is it possible in JavaScript?

const d = {
  A: () => { return 'A' },
  B: () => { return 'B' },
  C: () => { return 'C' },
}

const key = 'Z'

const func = d[key] // HERE

console.log(func)

I want to lookup for a key on an object, but if the key does't exist, it must return null, is it possible in JavaScript?

const d = {
  A: () => { return 'A' },
  B: () => { return 'B' },
  C: () => { return 'C' },
}

const key = 'Z'

const func = d[key] // HERE

console.log(func)

Share Improve this question edited Dec 15, 2021 at 13:50 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Dec 15, 2021 at 13:47 RodrigoRodrigo 54116 gold badges76 silver badges162 bronze badges 1
  • 1 Well you will get undefined, but if you really want null.. const func = d[key] || null – Keith Commented Dec 15, 2021 at 13:50
Add a ment  | 

3 Answers 3

Reset to default 5

You can use or: ||

or the newer optional chaining and Nullish coalescing operator

NOTE: the arrow function suggested by Máté Wiszt has to be wrapped in () or it will give an error

const d = {
  A: () => { return 'A' },
  B: () => { return 'B' },
  C: () => { return 'C' },
}

let key = 'A'

let func = d[key] || null;
console.log(func && func())

key = 'Z'

func = d[key] || null
console.log(func && func())

func = d[key] || function() { return null };
console.log(func && func())

func = d?.[key] ?? (() => null); // arrow has to be wrapped
console.log(func())

// undefined key
let key1;
console.log({key1})

func = d?.[key1] ?? (() => null); // arrow has to be wrapped
console.log("Using undefined key1:",func())

You can do:

const func = d[key] || () => null;

In this case you can call func safely.

It will be better to use hasOwnProperty to check wheather that property exist in the object d or not.

const d1 = {
  A: () => { return "A"; },
  B: () => { return "B"; },
  C: () => { return "C"; },
  Z: undefined,
};

const d2 = {
  A: () => { return "A"; },
  B: () => { return "B"; },
  C: () => { return "C"; },
};

const key = "Z";

function getValue(obj, key) {
  return obj.hasOwnProperty(key) ? obj[key] : null;
}

const func1 = getValue(d1, key);
console.log(func1);

const func2 = d1[key] || null;  // Shouldn't use
console.log(func2);

const func3 = d1[key] ?? null;  // Shouldn't use
console.log(func3);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744380961a4571427.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信