【问题标题】:Javascript - Read value of a JSON property, if that key doesn't exist return null, in a single lineJavascript - 读取 JSON 属性的值,如果该键不存在,则在一行中返回 null
【发布时间】:2017-03-30 14:09:10
【问题描述】:

让我对我正在寻找的东西进行一个 python 类比:

fruits_dict = {"banana": 4, "apple": 3}
num_apples = fruits_dict.get("apple", None)
num_oranges = fruits_dict.get("orange", None)
print(num_apples, num_oranges)

打印: 3 无

现在在 Javascript 中,有了类似的 JS 对象,我们可以在 if 块中使用 hasOwnProperty(key)

var fruits_obj = {"banana": 4, "apple": 3};
var num_apples = null;
if (fruits_obj.hasOwnProperty("apple")) {
    num_apples = fruits_obj["apple"];
}
var num_oranges = null;
if (fruits_obj.hasOwnProperty("orange")) {
    num_oranges = fruits_obj["orange"];
}
console.log(num_apples, num_oranges);

给出: 3 空

有没有更好的方法? python的get函数有什么东西吗?

【问题讨论】:

  • 嘿,@Razzildinho 已经给出了这个答案。还是谢谢。

标签: javascript python json


【解决方案1】:

如果你想从函数中返回它,在一行中,你可以使用三元:

return fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null;

【讨论】:

  • 使用 ECMAScript 2020 ::: return fruits_obj?.orange;
【解决方案2】:

你的代码确实没有问题,但是写起来会更简洁

num_oranges = ("orange" in fruits_obj) && fruits_obj.orange || null;

如果这很重要(可能不重要),这也会在对象的原型链中找到一个名为“orange”的属性。另外,请注意

num_oranges = fruits_obj.orange;

如果没有“oranges”属性,则将undefined 分配给num_oranges,并且出于许多实际目的,undefinednull 可以互换。 (例如,undefined == nulltrue。)

【讨论】:

  • 哇!好的。 dot 符号看起来很棒,我想我会使用它。应该在问之前测试一下。谢谢!
【解决方案3】:

您正在寻找ternary operator

var fruits_obj = {"banana": 4, "apple": 3};

var num_apples = fruits_obj.hasOwnProperty("apple") ? fruits_obj["apple"] : null;
var num_oranges = fruits_obj.hasOwnProperty("orange") ? fruits_obj["orange"] : null;

console.log(num_apples, num_oranges);

如果你想创建一个像 python get 这样的函数,它可能是这样的:

var getProp = function(object, key, default){
    return object.hasOwnProperty(key) ? object[key] : default;
};

var num_oranges = getProp(fruits_obj, "orange", null);

【讨论】:

  • 完全正确。这就是我要找的。加上@Pointy 所说的返回undefined 的点符号也是一个很好的建议。谢谢!
【解决方案4】:

您可以在原型对象中实现动态获取。

get: function(key) {
    if (typeof this[key] == 'undefined') return null;
    return this[key]
}

【讨论】:

    【解决方案5】:

    我们可以使用 JavaScript conditional (ternary) operator

    此运算符用作if statement 的快捷方式。

    语法:

    condition ? expr1 : expr2 
    

    如果条件为true,则运算符返回expr1的值;否则,它返回expr2 的值。

    var res = fruits_obj.hasOwnProperty("orange") ? fruits_obj['orange'] : null
    

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2021-04-04
      • 2018-06-17
      • 2014-03-19
      • 1970-01-01
      • 2018-11-09
      • 2018-04-10
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多