gpt4 book ai didi

JavaScript json数组输出

转载 作者:太空宇宙 更新时间:2023-11-04 16:17:29 27 4
gpt4 key购买 nike

有一个 JSON 字符串(缩短):

{"line_array":[{"short":"[common]","long":"undefined"},{"short":"_YES","long":"Yes"},{"short":"_NO","long":"No"},{"short":"_NOT","long":"Not "},{"short":"_SEARCH","long":"Search"},{"short":"_GO","long":"Go"}]}

我希望能够调用一个基于“短”值返回“长”值的函数:

喜欢:

var test= 'Say '+get_value("_YES");

我该怎么做?

尝试过:

function f_lang(short_string) {
var obj = json_string;
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

return arr['line_array'][short_string];
}

没有运气

最佳答案

使用Array#find找到包含短值的对象。请注意,IE 不支持 Array#find。因此,如果您需要 IE 支持和/或要进行大量此类转换,则应该采用字典方法。

var str = '{"line_array":[{"short":"[common]","long":"undefined"},{"short":"_YES","long":"Yes"},{"short":"_NO","long":"No"},{"short":"_NOT","long":"Not "},{"short":"_SEARCH","long":"Search"},{"short":"_GO","long":"Go"}]}';

var terms = JSON.parse(str);

function get_value(short) {
var term = terms.line_array.find(function(o) {
return o.short === short;
});

//in case the term isn't found, we'll prevent term.long from throwing an error
return term && term.long;
}

var result = get_value('_YES');

console.log(result);

使用字典对象

使用 Array#reduce 创建字典,并使用它:

var str = '{"line_array":[{"short":"[common]","long":"undefined"},{"short":"_YES","long":"Yes"},{"short":"_NO","long":"No"},{"short":"_NOT","long":"Not "},{"short":"_SEARCH","long":"Search"},{"short":"_GO","long":"Go"}]}';

var terms = JSON.parse(str);

var termsDictionary = terms.line_array.reduce(function(d, t) {
d[t.short] = t.long;
return d;
}, Object.create(null));

function get_value(short) {
return termsDictionary[short]; // you can use this expression without the function of course
}

var result = get_value('_YES');

console.log(result);

关于JavaScript json数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40959718/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com