【问题标题】:How to find data in JSON with unique keys?如何使用唯一键在 JSON 中查找数据?
【发布时间】:2021-05-25 15:42:30
【问题描述】:

我有一个包含数千条记录的 JSON 文件,如下所示:

{
    "001": [18.180555, -66.749961],
    "002": [18.361945, -67.175597],
    "003": [18.455183, -67.119887]
}

每个key 都是独一无二的。 value 是一个包含纬度和经度的数组。给定一个特定的key,我想提取经纬度。

在不知道最有效的方法(因为有数万条记录)的情况下,我正在尝试使用filter 方法。

let findKey = "002"
myJSON.filter(/*magic*/)

此外,我发现在搜索不存在的 key 时可以处理这种情况。比如findKey = "004",如何查看?

【问题讨论】:

  • 您可以使用data[findKey]。 (它看起来不像 JSON,而是一个 JS 对象。除非你在某处解析它)
  • lat: data[findKey][0] 和 long data[findKey][1]
  • @evolutionxbox 我正在读取一个.json 文件,它被解析为有效的JSON。
  • @decpk 这行得通。请添加答案,我会接受。

标签: javascript arrays json reactjs


【解决方案1】:

你可以通过bracket notation获取元素来查找元素:

const obj = {
  "001": [18.180555, -66.749961],
  "002": [18.361945, -67.175597],
  "003": [18.455183, -67.119887],
};

let findKey = "002";
if (obj[findKey]) {
  const lat = obj[findKey][0];
  const long = obj[findKey][1];
  console.log(lat, long);
}

let findKey2 = "004";
let lat2, long2;
if (obj[findKey2]) {
  lat2 = obj[findKey2][0];
  long2 = obj[findKey2][1];
  console.log(lat2, long2);
}

你也可以使用数组解构:

const obj = {
  "001": [18.180555, -66.749961],
  "002": [18.361945, -67.175597],
  "003": [18.455183, -67.119887],
};

let findKey = "002";
const arr = obj[findKey];
if (arr) {
  const [lat, long] = arr;
  console.log(lat, long);
}

let findKey2 = "004";
const arr2 = obj[findKey2];
if (arr2) {
  const [lat2, long2] = arr2;
  console.log(lat2, long2);
}

【讨论】:

  • 您能否添加如何检查findKey="004"?该键不存在,程序崩溃。
  • @Farhan 可能类似于:if(typeof arr != 'undefined') { do stuff } else { handle error }
【解决方案2】:

试试:

[lat, lng] = myJSON[findKey]
console.log(myJSON[findKey], lat, lng)

【讨论】:

    【解决方案3】:

    这是我的代码,您可以在其中获取未定义键的值(如果存在和“不存在”)

    const obj = {
        '001': [18.180555, -66.749961],
        '002': [18.361945, -67.175597],
        '003': [18.455183, -67.119887],
    };
    
    const find_key = '002';
    const [lt, lg] = typeof obj[find_key] == 'undefined' ? ['not exist', 'not exist'] : obj[find_key];
    
    console.log(lt, lg);
    

    【讨论】:

      【解决方案4】:

      可以直接解构为需要的变量:

      const obj = {"001":[18.180555,-66.749961],"002":[18.361945,-67.175597],"003":[18.455183,-67.119887]};
      
      const [lat, long] = obj?.["002"] ?? [,]
      console.log(lat, long)
      
      const [nLat, nLong] = obj?.["004"] ?? [,]
      console.log(nLat, nLong)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-05
        相关资源
        最近更新 更多