【问题标题】:Getting name of key with value null获取值为 null 的键名
【发布时间】:2017-06-30 19:14:10
【问题描述】:

我在我的数组中运行一个循环来检查calendartpoint 是否有值。在我的if-statementelse 声明中,我试图用var notSelected = (obj.prop.subProp).val() !== ''; 获取key 的名称。

我知道我的方法不对。我只是不确定如何获取密钥名称。

因此,在我的示例中,由于 tpoint 中的值是空的,我希望 var notSelected 等于 tpoint

有人知道我该怎么做吗?

var packageContents = {
    'packages': [
        {
            'price': '23',
            'name': 'Bronze Bundle Package',
            'calendar': {
                'type': '2year',
                'color': 'Brushed Nickel',
            },
            'tpoint': {
                'type': '',
                'touches': '',
                'years': '',
            }
        }
    ]
};

var bundleSet = null;

var bundleSet = null;
packageContents.packages.forEach(function (obj) {
    for (var prop in obj) {
        if (prop === 'calendar' || prop === 'tpoint') {
            for (var subProp in obj[prop]) {
                if (obj[prop][subProp] !== '') {
                    bundleSet = true;
                } else {
                    bundleSet = false;
                    var notSelected = (obj.prop.subProp).val() !== '';
                    console.log(notSelected);
                }
            }
        }

    }
    console.log(bundleSet);
});

【问题讨论】:

  • 引用obj.prop.subprop的那行是错误的;它应该是 obj[prop][subprop],就像在 if 语句中一样。对.val() 的调用也毫无意义;您只需要obj[prop][subprop],它将解析为“tpoint”对象的“type”、“touches”或“years”属性的值。
  • @Pointy 我试过做类似的事情...var notSelected = (obj[prop][subProp]).val() !== '';
  • 您应该会看到关于 .val() 引用的错误。
  • @Pointy 对,我知道.val 不是函数。我只是不确定如何构建它。
  • 去掉.val(),因为它没有意义。 obj[prop][subprop] 是解析为子属性值的表达式。您的代码已经使用它!无论如何,在您已经确定子属性值 ''. 之后,真的不清楚为什么还要麻烦地检查它再次

标签: javascript jquery arrays key


【解决方案1】:

这样的事情怎么样:

function hasEmptyProps(prop) {
  return Object.values(prop).some(x => x === '');
}

const result = packageContents.packages.map(x => {
  if (hasEmptyProps(x.calendar)) {
    return 'calendar';
  } else if (hasEmptyProps(x.tpoint)) {
    return 'tpoint'
  } else {
    return '';
  }
})

console.log(result)

将返回 ["tpoint"](或“日历”、“”或“tpoint”的数组)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多