我有一组具有wsDestAddress键的JSON对象,所以如何遍历JSON对象,或者在当前的JSON对象中疯狂搜索wsDestAddress键,以查找是否存在密钥,并返回null或""
JSON对象#1
{
"gfutd": {
"wsRequestData": {
"wsDestAddress": ""
}
}
}JSON对象#2
{
"igftd": {
"wsRequestData": {
"wsDestAddress": ""
}
}
}JSON对象#3
{
"y7igfutd": {
"wsResponseData": {
"wsDestAddress": ""
}
}
}JSON对象#4
{
"y7igptdf": {
"wsRequestData": {
"returnAddress": {
"wsDestAddress": ""
}
}
}
}我知道这个代码很好
if (y7igfutd.wsRequestData.wsDestAddress == "" ||
igftd.wsRequestData.wsDestAddress == "" ||
y7igfutd.wsResponseData.wsDestAddress == "" ||
y7igfutd.wsRequestData.returnAddress.wsDestAddress == "") {
return "result"
}但是我想对wsDestAddress进行疯狂的搜索,作为JSON键搜索。
发布于 2021-04-08 15:27:27
下面是使用目标扫描的一个答案。您的需求并不完全清楚,但我相信您可以轻松地调整下面的代码以满足您的需求。
// const objectScan = require('object-scan');
const data1 = { gfutd: { wsRequestData: { wsDestAddress: '' } } };
const data2 = { igftd: { wsRequestData: { wsDestAddress: '' } } };
const data3 = { y7igfutd: { wsResponseData: { wsDestAddress: '' } } };
const data4 = { y7igptdf: { wsRequestData: { returnAddress: { wsDestAddress: '' } } } };
const data5 = { y7igptdf: { wsRequestData: { returnAddress: { other: '' } } } };
const search = objectScan(['**.wsDestAddress'], {
filterFn: ({ value }) => value === '',
rtn: 'bool',
abort: true
});
console.log(search(data1));
// => true
console.log(search(data2));
// => true
console.log(search(data3));
// => true
console.log(search(data4));
// => true
console.log(search(data5));
// => false.as-console-wrapper {max-height: 100% !important; top: 0}<script src="https://bundle.run/object-scan@14.0.0"></script>
免责声明:我是目标扫描的作者
发布于 2021-04-08 12:42:16
您可以通过以下方法找到第一个具有"wsDestAddress"值为""的项:
const data = [
{ "y7igfutd" : { "wsResponseData" : { "wsDestAddress" : "" }}},
{ "igftd" : { "wsRequestData" : { "wsDestAddress" : "" }}},
{ "y7igfutd" : { "wsResponseData" : { "wsDestAddress" : "" }}},
{ "y7igptdf" : { "wsRequestData" : { "returnAddress" : { "wsDestAddress" : "" }}}}
];
// Adapted from: https://stackoverflow.com/a/40604638/1762224
const findValue = (object, key) => {
let value;
Object.keys(object).some(k => {
if (k === key) {
value = object[k];
return true;
}
if (object[k] && typeof object[k] === 'object') {
value = findValue(object[k], key);
return value !== undefined;
}
});
return value;
};
const oneMatches = (arr, key, value) =>
arr.some(item => findValue(item, key) === value);
const allMatches = (arr, key, value) =>
arr.every(item => findValue(item, key) === value);
console.log(oneMatches(data, 'wsDestAddress', '')); // Some = true
console.log(allMatches(data, 'wsDestAddress', '')); // Every = true
https://stackoverflow.com/questions/67003800
复制相似问题