react根据特定键检查数组值,如果找到值返回true/false



我正试图找出如何做到这一点,但似乎不能把我的头围绕它。

我有一个地址对象

const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123  Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}

我想检查任何有值的键,但只有特定的键

const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];

我想检查objProps中的所有键对我的地址对象,如果其中任何一个包含一个值返回true(不管它是1还是全部6)..如果所有键都不包含值,则返回false(有时我会得到一个所有值为空的地址对象)

我尝试了各种方法来完成这个任务,但每次都失败了。

我现在正在工作的变化是使用减少。虽然它不满足我的需要,我想我可以检查结果数组,如果长度大于0比我有我的答案..

在制品:

function hasAddressData(obj: any) {
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const keysWithData = objProps.reduce((accumulator, key) => {
const propExistsOnObj = obj.hasOwnProperty(key);
let keyHasData = [];
if (obj[key].length > 0 ) {
keyHasData = obj[key]
}
if (!propExistsOnObj) {
accumulator.push(key);
} else if (keyHasData) {
const equalValueKeyIndex = accumulator.indexOf(key);
accumulator.splice(equalValueKeyIndex, 1);
}
return accumulator;
});
return keysWithData;
}

我知道上面的内容是混乱的,并且不起作用。只是在学习这些东西…有人有什么建议或评论吗?

检查.someobjProps,当obj抬起头,包含一个值。(与Boolean或与''比较)

const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123  Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);

const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"",
"addressLine2":"",
"city":"",
"state":"Indiana",
"state_code":"",
"zip":"",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":""
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);

function checkKeys(target, props) {
return props.some((prop) => {
return target.hasOwnProperty(prop) && target[prop];
});
}

解释:some遍历你想要检查的道具,当找到一个时立即返回true(即回调返回true)。如果没有找到props(即没有回调返回true),则some返回false

hasOwnProperty确保您只检查target上的属性,而不是查找原型链。target[prop]检查真值。如果你要处理字符串以外的值,你可能需要修改这最后一个检查。

相关内容