如何在JSON对象数组中匹配字符串并获取对应值?
匹配数组键获取对应值的解决方案
需求说明
给定包含单个键值对对象的数组,需遍历数组,匹配目标键 ss@d.com 并获取其对应值。
实现思路
遍历数组中的每一个对象,检查当前对象是否包含目标键,若存在则直接取出对应的值即可。
代码示例(JavaScript)
const arr = [{"nn@g.com":"custom"}, {"ss@d.com":"free"}, {"p23@gmail.com":"free"}]; const targetKey = "ss@d.com"; let result; for (const obj of arr) { if (obj.hasOwnProperty(targetKey)) { result = obj[targetKey]; break; // 找到后终止遍历,提升效率 } } console.log(result); // 输出: free
结果说明
运行上述代码后,会输出目标键对应的 free 值。
内容的提问来源于stack exchange,提问作者Pralayasimha Yedida
相关产品推荐
相关产品推荐

