简体   繁体   English

如果索引不存在,则获取对象中的数据

[英]Get data in object if index doesn't exist

I have a object with data like this: 我有一个数据如下的对象:

var data = {
    '4': [1, 2, 3],
    '5': [1, 2, 3],
    '6': [1, 2, 3],
    '7': [1, 2, 3],
    '8': [1, 2, 3],
    '9': [1, 2, 3],
    '10': [1, 2, 3],
    '11': [1, 2, 3],
    '12': [1, 2, 3],
    '15': [1, 9, 3],
    '18': [1, 2, 3],
    '21': [1, 8, 3],
    '24': [1, 2, 3],
    '30': [1, 2, 3],
    '36': [1, 2, 3],
    '42': [1, 20, 3]
}

Now I want to access the data like 现在我想像这样访问数据

var result = data[i][1];

This would give me a result of 9 if i = 15 . 如果i = 15这将给我9的结果。

But I need to get always the next lower index, if the given index isn't existing. 但是,如果给定的索引不存在,则需要始终获取下一个较低的索引。 So, if i = 16 the result should also be 9 . 因此,如果i = 16则结果也应为9 If i = 23 the result is 8 and for i = 999 , the result is 20 . 如果i = 23则结果为8 ;对于i = 999 ,结果为20 How can I do that? 我怎样才能做到这一点?

You're going to have to loop downwards searching for that property in your array. 您将不得不向下循环以在数组中搜索该属性。 Assuming input is the one you're trying to find, 假设input是您要查找的输入,

for (var i = input; i > 0; i--) { // Looping incrementing down
    if (data.hasOwnProperty(i)) {
        result = data[i][1];
        break;
    }
}

The hasOwnProperty method checks if your data array has that index available, and breaks out of the loop after setting result if it does. hasOwnProperty方法检查您的数据数组是否有可用的索引,如果设置了索引,则在设置result后退出循环。

You need to look for the index request, and if you don't find it, subtract one from the index and try again. 您需要查找索引请求,如果找不到,请从索引中减去一个,然后重试。 Something like: 就像是:

function getItem(i,j) {
    if (i < 0) {
        // assuming no negative keys exists
        return null;   // or throw an error if you prefer
    }
    if (data[i]) {
        return data[i][j];
    }
    else {
         return getItem(i-1,j);
    }
}

Usage: 用法:

getItem(16,1);    // should give you 9

To round it to the closest number ether way, try using this: 要将其四舍五入到最接近的数字以太方式,请尝试使用以下方法:

var data = {
    '4': [ 1, 2, 3 ],
    '5': [ 1, 2, 3 ],
    '6': [ 1, 2, 3 ],
    '7': [ 1, 2, 3 ],
    '8': [ 1, 2, 3 ],
    '9': [ 1, 2, 3 ],
    '10': [ 1, 2, 3 ],
    '11': [ 1, 2, 3 ],
    '12': [ 1, 2, 3 ],
    '15': [ 1, 9, 3 ],
    '18': [ 1, 2, 3 ],
    '21': [ 1, 8, 3 ],
    '24': [ 1, 2, 3 ],
    '30': [ 1, 2, 3 ],
    '36': [ 1, 2, 3 ],
    '42': [ 1, 20, 3 ]
}

var keys = $.map( data, function ( element, index ) {
    return index
} );

function closest( number ) {
    var closest = null;
    $.each( keys, function () {
        if ( closest == null || Math.abs( this - number ) < Math.abs( closest - number ) ) {
            closest = this;
        }
    } );
    return closest;
}

console.log( data[closest( 16 )][1] );

Thanks to: https://stackoverflow.com/a/3561328/5414240 for the closest function. 感谢: https : //stackoverflow.com/a/3561328/5414240提供最接近的功能。

Hope this helps. 希望这可以帮助。

For a valid key I would suggest 对于有效的钥匙,我建议

  1. try if the key exists, or 尝试是否存在密钥,或者
  2. get all keys, map them to Number , perform a numerical sort and at least reduce the data to a key, which is smaller than the next bigger value. 获取所有键,将它们映射到Number ,执行数字排序,并至少将数据缩减为小于下一个较大值的键。

 var data = { '4': [1, 2, 3], '5': [1, 2, 3], '6': [1, 2, 3], '7': [1, 2, 3], '8': [1, 2, 3], '9': [1, 2, 3], '10': [1, 2, 3], '11': [1, 2, 3], '12': [1, 2, 3], '15': [1, 9, 3], '18': [1, 2, 3], '21': [1, 8, 3], '24': [1, 2, 3], '30': [1, 2, 3], '36': [1, 2, 3], '42': [1, 20, 3] }; function getKey(key) { return key in data ? key : Object.keys(data).map(Number).sort(function (a, b) { return a - b; }).reduce(function (r, a) { return a <= key ? a : r; }); } document.write('3 ' + getKey(3) + '<br>'); document.write('15 ' + getKey(15) + '<br>'); document.write('16 ' + getKey(16) + '<br>'); document.write('23 ' + getKey(23) + '<br>'); document.write('999 ' + getKey(999) + '<br>'); 

Edit: For even better performance, avoids inspection of all items in the keys array. 编辑:为获得更好的性能,请避免检查keys数组中的所有项目。 The solution works for sparse arrays as well, like 该解决方案也适用于稀疏数组,例如

var data = [];
data[4] = [1, 2, 3];
data[5] = [1, 2, 3];
data[6] = [1, 2, 3];

 var data = { '4': [1, 2, 3], '5': [1, 2, 3], '6': [1, 2, 3], '7': [1, 2, 3], '8': [1, 2, 3], '9': [1, 2, 3], '10': [1, 2, 3], '11': [1, 2, 3], '12': [1, 2, 3], '15': [1, 9, 3], '18': [1, 2, 3], '21': [1, 8, 3], '24': [1, 2, 3], '30': [1, 2, 3], '36': [1, 2, 3], '42': [1, 20, 3] }, keys = Object.keys(data).map(Number).sort(function (a, b) { return a - b; }), i; function getKey(key) { var lower = 0, upper = keys.length - 1, index; if (key in data) { return key; } if (key < keys[0]) { return; // this is not specified in question } if (key > keys[upper]) { return keys[upper]; } while (lower !== upper) { index = lower + upper >> 1; if (key > keys[index]) { lower = index + 1; continue; } upper = index; } return keys[lower - 1]; } for (i = -5; i < 50; i++) { document.write('value: '+ i + ', key: ' + getKey(i) + '<br>'); } 

If the data-structure is similar to a sparse array and if the indices of this data-structure tend to be bigger integer representatives, then a "try-and-error count-down approach" with stepwise decreasing a given index by 1 might not perform anymore that well. 如果数据结构类似于稀疏数组,并且如果该数据结构的索引趋向于更大的整数表示,则逐步将给定索引递减1的“尝试错误倒数方法”可能不会表现再好。

The following example tries to take this into account ... 以下示例尝试考虑到这一点...

var getNextLowerOrSameIndex = function (obj, idx) {
  var
    indexCount,
    listOfIndices
  ;
  idx = parseInt(idx, 10);

  if (!(idx in obj)) {
    listOfIndices = Object.keys(obj);

    idx = (listOfIndices.every(function (index, count/*, listOfIndices*/) {

      indexCount = count;
      index = parseInt(index, 10);

      listOfIndices[indexCount] = index;

      return (idx > index);

    }) && Math.max.apply(null, listOfIndices)) || listOfIndices[indexCount - 1];
  }
//return idx;
  return (Number.isFinite(idx) && idx) || (void 0);
};

... ...

var data = {
  '4': [1, 2, 3],
  '5': [1, 2, 3],
  '6': [1, 2, 3],
  '7': [1, 2, 3],
  '8': [1, 2, 3],
  '9': [1, 2, 3],
  '10': [1, 2, 3],
  '11': [1, 2, 3],
  '12': [1, 2, 3],
  '15': [1, 9, 3],
  '18': [1, 2, 3],
  '21': [1, 8, 3],
  '24': [1, 2, 3],
  '30': [1, 2, 3],
  '36': [1, 2, 3],
  '42': [1, 20, 3]
};

console.log(data[getNextLowerOrSameIndex(data, 4)][1]);     // 2
console.log(data[getNextLowerOrSameIndex(data, "4")][1]);   // 2
console.log(data[getNextLowerOrSameIndex(data, "5")][1]);   // 2

console.log(data[getNextLowerOrSameIndex(data, 15)][1]);    // 9
console.log(data[getNextLowerOrSameIndex(data, 16)][1]);    // 9
console.log(data[getNextLowerOrSameIndex(data, "15")][1]);  // 9
console.log(data[getNextLowerOrSameIndex(data, "17")][1]);  // 9

console.log(data[getNextLowerOrSameIndex(data, "23")][1]);  // 8
console.log(data[getNextLowerOrSameIndex(data, 999)][1]);   // 20

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM