1

我有一组具有wsDestAddress密钥的 JSON 对象,那么如何遍历 JSON 对象或wsDestAddress在现有 JSON 对象中疯狂搜索密钥以查找密钥是否存在并返回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 键搜索。

4

2 回答 2

1

您可以找到"wsDestAddress"值为""via 的第一项:

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

于 2021-04-08T12:42:16.510 回答
1

这是使用object-scan的答案。您的要求并不完全清楚,但我相信您可以轻松调整以下代码以满足您的需求。

// 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-08T15:27:27.677 回答