You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从包含map元素的list中提取author和text对应的值

操作思路

直接遍历列表中的每个Map元素,按key取值即可,不同常用编程语言的实现代码如下:

1. Python 实现
# 遍历打印每一条的作者和名言
for quote in quotes:
    author = quote["author"]
    text = quote["text"]
    print(f"作者:{author},名言:{text}")

# 若需要把取出的结果整理为新列表
extract_list = [{"author": q["author"], "text": q["text"]} for q in quotes]
2. Dart(Flutter)实现
// 基础遍历取值
for (var quote in quotes) {
  String author = quote["author"];
  String text = quote["text"];
  print("作者:$author,名言:$text");
}

// 规范开发建议:先转成实体类再使用
class Quote {
  final String author;
  final String text;
  Quote({required this.author, required this.text});
  
  factory Quote.fromMap(Map map) {
    return Quote(
      author: map["author"] ?? "", 
      text: map["text"] ?? ""
    );
  }
}
// 批量转换为实体类列表
List<Quote> quoteObjs = quotes.map((e) => Quote.fromMap(e)).toList();
3. JavaScript 实现
// 遍历取值
quotes.forEach(quote => {
  const author = quote.author
  const text = quote.text
  console.log(`作者:${author},名言:${text}`)
})

// 提取为新数组
const result = quotes.map(({author, text}) => ({author, text}))
注意事项

如果不能保证每个Map元素都一定存在author和text两个key,建议先做判空处理,避免取值时报空指针/键不存在的异常。


内容的提问来源于stack exchange,提问作者GAURAV JOSHI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 10:24:01