我正在尝试检查calendar
和tpoint
键是否具有与之关联的值。
首先,我尝试检查是否包含calendar
和tpoint
键,但后来我意识到它们总是像键一样。我想查看calendar
和tpoint
键是否有价值的原因,因为有时他们会赢。
我的尝试低于下面的packageContents
对象。
有谁知道如何检查密钥是否有值?
var packageContents = {
'packages': [
{
'price': '32',
'name': 'Gold Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': 'Gold',
'touches': '21',
'years': '7',
}
},
{
'price': '23',
'name': 'Bronze Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': 'Bronze',
'touches': '9',
'years': '7',
}
}
]
};
packageContents['packages'].forEach(function (bun) {
if (bun['calendar'].length >= 1 && bun['tpoint'].length >= 1) {
var bundleSet;
console.log(bundleSet);
console.log('Working');
}
});
编辑:
var packageContents = {
'packages': [
{
'price': '23',
'name': 'Bronze Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': '',
'touches': '',
'years': '',
}
}
]
};
var bundleSet = '';
packageContents['packages'].forEach(function (obj) {
if (typeof obj.calendar !== 'undefined' && typeof obj.tpoint !== 'undefined') {
bundleSet = "Bundle";
}
else {
bundleSet = "not bundle"
}
console.log(bundleSet);
});
答案 0 :(得分:3)
您的.forEach()
循环正在循环packageContent.packages
数组中的对象,因此最好使用变量名称来提醒您。
然后,由于您知道这些对象中的键的静态名称,因此您不需要使用括号表示法([]
)将它们作为字符串传递给对象,您只需使用点表示法在实例上。
最后,您只想查看这些密钥中是否存储了值,因此请检查存储在那里的数据类型是否为undefined
。
var packageContents = {
'packages': [
{
'price': '32',
'name': 'Gold Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': 'Gold',
'touches': '21',
'years': '7',
}
},
{
'price': '23',
'name': 'Bronze Bundle Package',
'calendar': {
'type': '2year',
'color': 'Brushed Nickel',
},
'tpoint': {
'type': '',
'touches': '',
'years': '',
}
}
]
};
var bundleSet = null;
packageContents.packages.forEach(function (obj) {
// We are now looping over each top-level object in the main array.
// To see if each of the properties in quesiton of those objects have values,
// we need to loop over those properties
for(var prop in obj){
// We're only interested in "calendar" and "tpoint"
if(prop === "calendar" || prop === "tpoint"){
// These properties store objects of their own and it is these properties we need to check
for(var subProp in obj[prop]){
// Since you know the key names, you can access them directly on the instance
// and simply see if they have values by checking that they are not undefined
if (obj[prop][subProp] !== "") {
bundleSet = true;
} else {
bundleSet = false;
}
}
}
}
console.log(bundleSet);
});