假设我有一个这样的对象:
var myData = {hex_index: "8d26745060122bf", val_1: 2.003234, val_2: 2.0022008, val_3: 2.0044124, val_4: 2.0045183, val_5: 3.012644, val_6: 1.8760033, val_7: 123.0203457};
给定一个具有给定int值的变量,例如:
const valueRI = 2;
如何找到最接近2的值,并且不返回该值,而是返回密钥(例如:"val2"(?我有一个函数可以返回精确匹配的密钥,它的"最接近的鳍"部分给我带来了麻烦:
const selectRI = () => {
valueRI = document.getElementById("selectInterval").value;
console.log(valueRI);
Object.values(myData).forEach(
function(value) {
if (value === valueRI) {
console.log(Object.keys(masterObj).find(key => masterObj[key] === value));
}
}
);
}
根据valueRI
和值之间的绝对差对Object.entries(masterObj)
进行排序。然后返回第一个键。
var myData = {
hex_index: "8d26745060122bf",
val_1: 2.003234,
val_2: 2.0022008,
val_3: 2.0044124,
val_4: 2.0045183,
val_5: 3.012644,
val_6: 1.8760033,
val_7: 123.0203457
};
const selectRI = (valueRI) => {
const sorted = Object.entries(myData).filter(([k, v]) => k.startsWith('val_')).sort(([k1, v1], [k2, v2]) =>
Math.abs(valueRI - v1) - Math.abs(valueRI - v2));
return sorted[0][0];
}
console.log(selectRI(100));
console.log(selectRI(3.1));
遍历对象,记下距离目标最小的值。
var myData = {
hex_index: "8d26745060122bf",
val_1: 2.003234,
val_2: 2.0022008,
val_3: 2.0044124,
val_4: 2.0045183,
val_5: 3.012644,
val_6: 1.8760033,
val_7: 123.0203457
};
const valueRI = 2;
// first calculate the distance of each value from the target
// set a variable that houses the smallest distance found so far
// and the key of the smallest distance found so far
let smallestDistance = true
let smallestKey = null
Object.keys(myData).forEach(key => {
let distance = Math.abs(valueRI - myData[key])
if (distance <= smallestDistance) {
smallestDistance = distance
smallestKey = key
}
})
console.log(`The key with the smallest distance was ${smallestKey}, it was ${smallestDistance} away from ${valueRI}`)