【问题标题】:iteration in javascript, nodejs [closed]javascript,nodejs中的迭代[关闭]
【发布时间】:2019-12-06 10:54:24
【问题描述】:

我有这样的数据: -

[
{"title": "A Hug Is Warm","id": "69","level": "4","act_title": "Alphabet","act_id": "69_1d"},
{"title": "A Hug Is Warm","id": "69","level": "4","act_title": "Recording","act_id": "69_rec"},
{"title": "A Hug Is Warm","level": "4","id": "69","act_title": "Print","act_id": "69_pr_1"},
.........
];

又想回来:......

[{
        "title": "A Hug Is Warm",
        "id": "69",
        "level": "4",
        "activities": [{"act_title": "Alphabet",act_id": "69_1d"},
            {"act_title": "Recording","act_id": "69_rec"},
            {"act_title": "Print","act_id": "69_pr_1"}
        ]
    },
    ..........
]

在php中使用多维数组很容易实现。

【问题讨论】:

    标签: javascript node.js multidimensional-array


    【解决方案1】:

    你可以使用Array.reduce():

    var arr = [{
        "title": "A Hug Is Warm",
        "id": "69",
        "level": "4",
        "act_title": "Alphabet",
        "act_id": "69_1d"
      },
      {
        "title": "A Hug Is Warm",
        "id": "69",
        "level": "4",
        "act_title": "Recording",
        "act_id": "69_rec"
      },
      {
        "title": "A Hug Is Warm",
        "level": "4",
        "id": "69",
        "act_title": "Print",
        "act_id": "69_pr_1"
      },
      {
        "title": "A Hug Is Warm",
        "id": "70",
        "level": "4",
        "act_title": "Alphabet",
        "act_id": "69_1d"
      },
      {
        "title": "A Hug Is Warm",
        "id": "70",
        "level": "4",
        "act_title": "Recording",
        "act_id": "69_rec"
      },
      {
        "title": "A Hug Is Warm",
        "level": "4",
        "id": "70",
        "act_title": "Print",
        "act_id": "69_pr_1"
      }
    ];
    
    var res = arr.reduce((acc, item) => {
      let existItem = acc.find(({id}) => id === item.id);
      if (existItem) {
        existItem.activities.push({
          act_title: item.act_title,
          act_id: item.act_id
        });
      } else {
        acc.push({
          title: item.title,
          level: item.level,
          id: item.id,
          activities: [{
            act_title: item.act_title,
            act_id: item.act_id
          }]
        });
      }
      return acc;
    }, []);
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2014-01-28
      • 2022-09-23
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      相关资源
      最近更新 更多