如何在飞镖中弄平一个嵌套的阵列?

发布于 2025-02-03 00:38:47 字数 851 浏览 1 评论 0原文

我如何弄平一个嵌套的阵列?

[
  {
    "page": 1,
    "items": [
      {
        "addresses": [
          "hello1",
          "hello2"
        ]
      }
    ]
  },
  {
    "page": 2,
    "items": [
      3,
      {
        "addresses": [
          "hello3",
          "hello4"
        ]
      }
    ]
  },
  {
    "page": 3,
    "items": [
      3,
      4
    ]
  }
];

所需的输出IST:

["hello1", "hello2", "hello3", "hello4"]
import 'dart:convert';

main() {
  const jsonString =
      '[{"page":1, "items": [{"addresses": ["hello1","hello2"]}]}, {"page":2, "items": [3, {"addresses": ["hello3","hello4"]}]}, {"page":3, "items": [3, 4]}]';
  final items = jsonDecode(jsonString) as List;
  final x = items.expand((p) => p["items"]).expand((p) => p["addresses"]);
  print(x);
}

How do I flatten a nested array?

[
  {
    "page": 1,
    "items": [
      {
        "addresses": [
          "hello1",
          "hello2"
        ]
      }
    ]
  },
  {
    "page": 2,
    "items": [
      3,
      {
        "addresses": [
          "hello3",
          "hello4"
        ]
      }
    ]
  },
  {
    "page": 3,
    "items": [
      3,
      4
    ]
  }
];

Desired output ist:

["hello1", "hello2", "hello3", "hello4"]
import 'dart:convert';

main() {
  const jsonString =
      '[{"page":1, "items": [{"addresses": ["hello1","hello2"]}]}, {"page":2, "items": [3, {"addresses": ["hello3","hello4"]}]}, {"page":3, "items": [3, 4]}]';
  final items = jsonDecode(jsonString) as List;
  final x = items.expand((p) => p["items"]).expand((p) => p["addresses"]);
  print(x);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绾颜 2025-02-10 00:38:47

好的,所以您有一个看起来像这样的地图列表:

{
  page: int,
  items: List<{
    addresses: List<String>
  }>

有时这些项目只是数字,您想在单个列表上获取所有地址,这就是我的方式:

List<String> result = [];

p.forEach((obj) {
  final objMap = obj as Map<String, dynamic>
  objMap['items'].forEach((item) {
    if (item is Map<String, dynamic>) {
      result.addAll(item['addresses'] as List<String>);
    }
  });
});

有点笨拙,我知道,但是我认为这会解决这个问题

Ok, so you have a list of maps that look like this:

{
  page: int,
  items: List<{
    addresses: List<String>
  }>

except sometimes the items are just numbers, you want to get all addresses on a single list, here is how I would do it:

List<String> result = [];

p.forEach((obj) {
  final objMap = obj as Map<String, dynamic>
  objMap['items'].forEach((item) {
    if (item is Map<String, dynamic>) {
      result.addAll(item['addresses'] as List<String>);
    }
  });
});

A bit clunky, I know, but I think it will do the trick

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文