【问题标题】:How to sort array in JSON to get value of specific index?如何对 JSON 中的数组进行排序以获取特定索引的值?
【发布时间】:2020-12-11 04:49:17
【问题描述】:

您好,我对 JSON 和 API 非常陌生,并且正在研究一个我在数组中获取价值的 API。

{
   id: 0,
   text: "one"
}
{
   id: 1,
   text: "two"
}
{
   id: 2,
   text: "three"
}

我只想要一个数组的值,其中id=0 并且我不知道如何在 JSON 中对数组进行排序来实现这一点,我使用 ajax 来获取这个值

async function getDataFromId() {
    let url = 'API_URL';
    let Qid = 1;
    let result;
    try {
        result = await jQuery.ajax({
            url: url,
            type: 'GET',
            contentType: 'application/json',
        });
        result = result.sort((a, b) => a.id- b.id);
        console.log(result)
    }catch (error) {
        console.error(error);
    }
}

【问题讨论】:

  • 如果只想要id=0的值,为什么还要排序呢?过滤还不够吗?
  • @Turtlean 很抱歉,这是非常菜鸟的事情,但是如何过滤?
  • 试试这个:var new_array = result.filter(function(i){return i.id == 0})

标签: javascript jquery arrays json


【解决方案1】:

您无需对数组进行排序即可获得 id == 0 的对象。 使用 Array#find 找到你想要的对象。


let myObject = myArr.find((_o)=>_o.id === 0);

【讨论】:

    【解决方案2】:

    也许是这样的:

    if(result){
      resultSorted = result.sort((a, b) => a.id - b.id);
      resultFiltered = result.filter(x => x.id == 0);
    }

    【讨论】:

      【解决方案3】:

      我只想要 id=0 的数组的值

      您正在根据 ID 正确地对 ascendant order 中的结果进行排序,因此剩下的唯一事情就是创建一个仅包含第一个元素的数组:

      result = result.sort((a, b) => a.id- b.id)
      console.log([result[0])
      

      您可以利用您所追求的条件来filter 数组。在这种情况下:id === 0。这将删除与条件不匹配的元素(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter):

      result = result.filter((a) => a.id === 0)
      console.log(result)
      

      请记住,sorting 数组比 filtering 更昂贵,所以如果您只想保留带有 id === 0 的数组,我肯定会选择 filter 选项

      【讨论】:

        【解决方案4】:

        以上所有答案都很好,但您使用的是变量Qid

        result = result.filter(function(i){return i.id === Qid});
        console.log(resulr)
        

        你不需要排序,你可以过滤它,这对你的工作来说会更容易

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-22
          • 1970-01-01
          • 2018-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多