问题描述
如何判断一个对象是否有值?
我的对象如下所示:我必须遍历对象数组并检查数组的值中是否包含“SPOUSE”。如果存在 set a flag spouseExits = true
和 store the number (in this case (4 because [SPOUSE<NUMBER>] NUMBER is 4) in a variable 'spouseIndex'
此功能也需要在 IE9 中呈现。
eligibilityMap = {
"CHIP": [
"CHILD5"
],"APTC/CSR": [
"SELF1","CHILD2","CHILD3","SPOUSE4"
]
}
代码:
Object.keys(eligibilityMap).reduce(function (acc,key) {
const array1 = eligibilityMap[key];
//console.log('array1',array1);
array1.forEach(element => console.log(element.indexOf('SPOUSE')))
var spouseExist = array1.forEach(function (element) {
//console.log('ex',element.indexOf('SPOUSE') >= 0);
return element.indexOf('SPOUSE') >= 0;
});
//console.log('spouseExist',spouseExist);
return acc;
},{});
SpouseIndex 未定义。我做错了什么?
解决方法
解决方案 1:执行 3 个步骤
-
您可以使用
flatMap
将所有子数组合二为一。 -
使用
findIndex
结合startsWith
精确获取SPOUSE
的索引 -
根据找到的索引值分配 2 个变量。
const eligibilityMap = { "CHIP": [ "CHILD5" ],"APTC/CSR": ["SELF1","CHILD2","CHILD3","SPOUSE4"]};
let SpouseExits = false,SpouseIndex = 0;
const arrays = Object.values(eligibilityMap).flatMap(r => r);
const index = arrays.findIndex(str => str.startsWith("SPOUSE"));
if(index >= 0){
SpouseExits = true;
SpouseIndex = arrays[index].slice(-1);
}
console.log({SpouseExits,SpouseIndex});
解决方案 2:该函数也可以在 IE9 中呈现
const eligibilityMap = { "CHIP": [ "CHILD5" ],SpouseIndex = 0;
for(const [key,value] of Object.entries(eligibilityMap))
{
const index = value.findIndex(function(str){ return str.startsWith("SPOUSE")});
if(index >= 0){
SpouseExits = true;
SpouseIndex = value[index].slice(-1);
}
}
console.log({SpouseExits,SpouseIndex});
这是一个简单的方法,支持包括IE在内的所有浏览器:
var spouseExists = false;
var spouseNumber;
for(var key in eligibilityMap)
{
for(var index in eligibilityMap[key])
{
if (eligibilityMap[key][index].indexOf("SPOUSE") > -1)
{
spouseExists = true;
spouseNumber = eligibilityMap[key][index].replace("SPOUSE",'');
break;
}
}
}
console.log(spouseExists,spouseNumber);
,
您的条件 element.indexOf('SPOUSE') >= 0
不匹配数组中的任何值配偶,因为您的数组没有名为配偶 SPOUSE
的值,但它具有 SPOUSE4
。
这就是它返回 undefined 的原因。
您可以使用正则表达式代替直接匹配,
Object.keys(eligibilityMap).reduce(function (acc,key) {
const array1 = eligibilityMap[key];
//console.log('array1',array1);
// array1.forEach(element => console.log(element.indexOf('SPOUSE')))
// var spouseExist = -1;
var spouseExist = array1.filter(function (element,index) {
if(element.match(/SPOUSE/g)) return element; //fixes
});
//fixes
console.log('spouseExist',spouseExist.length>0)
if(spouseExist.length>0){
spouseExist.forEach(element => {
console.log('spouseIndex',element[element.length-1])
});
}
return acc;
},{});
您可以直接从配偶姓名中获取编号,也可以使用 index
的值从过滤器函数内部访问匹配配偶的索引编号,然后随心所欲。
希望这符合您的要求。