如何从功能参数中指定的json数组中获取密钥而不循环?

时间:2018-07-08 10:17:16

标签: javascript jquery json

我有示例json数组:

var jsonArray = '{"name":"Otabek","lastName":"Mansurov","age":"16"}';

我有示例功能:

function getError(jsonArray, arrayKeyFromJsonArray) {
    var looping = $.parseJSON(jsonArray);
    $.each(looping, function(key, value) {
        if(key.toLowerCase() == arrayKeyFromJsonArray.toLowerCase()) {
            console.log(key + '=' + value);
        } else console.log("Sorry, I can't found key " + arrayKeyFromJsonArray + " from array!");
    });
}

使用示例:

getError(jsonArray, 'age'); // Return: age = 16

是否可以从没有循环的数组中找到键?

新函数伪代码示例:

function getError(jsonArray, arrayKeyFromJsonArray) {
    return jsonArray.arrayKeyFromJsonArray;
}

3 个答案:

答案 0 :(得分:1)

由于键是区分大小写的,因此无法使用惰性样式。

您可以使用Array#find并检查值,如果没有,undefined将其用作对象的键。

function getError(json, search) {
    var object = JSON.parse(json),
        key = Object.keys(object).find(k => k.toLowerCase() === search.toLowerCase());
        
    return key !== undefined
        ? object[key]
        : "Sorry, I can't find key " + search + " in array!"
}

var json = '{"name":"Otabek","lastName":"Mansurov","age":"16"}';

console.log(getError(json, 'age'));
console.log(getError(json, 'lastname'));
console.log(getError(json, 'foo'));

答案 1 :(得分:0)

您想动态获取密钥数据,因为使用不知道密钥将是什么。 对于这种情况,您可以尝试类似

  

循环[arrayKeyFromJsonArray]

function getError(jsonArray, arrayKeyFromJsonArray) {
    var looping = $.parseJSON(jsonArray);
    console.log(arrayKeyFromJsonArray + '=' + looping[arrayKeyFromJsonArray]);

}

答案 2 :(得分:0)

我认为最好也检查错误,您可以使用x <- c(0, 100, 200, 300, 400, 500, 600, 700, 800, 700, 600, 500, 400, 300, 200, 100, 0) y <- c(7.93, 8.38, 8.79, 9.08, 9.4, 9.72, 10.04, 10.35, 10.66, 10.37, 10.06, 9.73, 9.41, 9.06, 8.64, 8.36, 7.93) x_name <- "gewicht" y_name <- "auslenkung" df <- data.frame(x,y) names(df) <- c(x_name, y_name) plot(df$gewicht, df$auslenkung, xaxt = "n", yaxt = "n", col = "red", xlab = "Belastung [g]", ylab = "Längenänderung [mm]", main = "Änderung des Länge eines Messingdrahtes", frame.plot = FALSE) axis(1, at = seq(0, 800, by = 100), las= 2) axis(2, at = seq(7.5, 11, by = 0.5), las= 2) fit1 <- lm(auslenkung ~ gewicht, data = df) abline(fit1, lty = "dashed") text(x = , y = 0,labels= "slope = 3.391e-03 \n intercept = 8.012e+00 \n R2 = 0.9967 \n P = 2.2e-16") 关键字:

in
var jsonArray = '{"name":"Otabek","lastName":"Mansurov","age":"16"}';
function getError(jsonArray, arrayKeyFromJsonArray) {
  var looping = $.parseJSON(jsonArray);
  if( arrayKeyFromJsonArray in looping )
      return looping[arrayKeyFromJsonArray];
   else {
      console.log("key not found");
      return undefined; // or null
   }
}

console.log( getError( jsonArray, "age" ) );
console.log( getError( jsonArray, "XXX" ) );