【问题标题】:compare two array and put a status in an other array if it exist or not比较两个数组并将状态放入另一个数组(如果存在与否)
【发布时间】:2022-06-15 22:09:04
【问题描述】:

所以我有一个包含所有玩家的数组,一个只包含一个被选中的数组,如果他被选中,我想要另一个数组的状态。我尝试将元素与状态进行比较和推送,但没有达到我想要的。

这是数组

  const all = [
    {
      playerId: '294',
      firstName: 'MMM',
    },
    {
      playerId: '295',
      firstName: 'arkiv',
    },
    {
      playerId: '296',
      firstName: 'julio',
    },
    {
      playerId: '297',
      firstName: 'sss',
    },
  ];

const selected = [
    {
      playerId: '296',
      firstName: 'julio',
    },
    {
      playerId: '297',
      firstName: 'sss',
    },
  ];

这就是我想要达到的目标

  const res = [
    { playerId: '294', firstName: 'MMM', status: false },
    { playerId: '295', firstName: 'arkiv', status: false },
    { playerId: '296', firstName: 'julio', status: true },
    { playerId: '297', firstName: 'sss', status: true },
  ];

我在这里设置了一个工作环境:https://stackblitz.com/edit/react-lkcqcd?file=src%2FApp.js

感谢关注!

【问题讨论】:

    标签: javascript arrays json


    【解决方案1】:

    您可以使用Array#some 来检查玩家的id 是否在选定的数组中。

    const all=[{playerId:'294',firstName:'MMM',},{playerId:'295',firstName:'arkiv',},{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},],selected=[{playerId:'296',firstName:'julio',},{playerId:'297',firstName:'sss',},];
    all.forEach(player => player.status = 
                  selected.some(x => x.playerId === player.playerId));
    console.log(all);

    【讨论】:

      【解决方案2】:

      您可以创建选定玩家的Set,并使用此集合添加status 字段。

      const 
        all = [
          { playerId: "294", firstName: "MMM" },
          { playerId: "295", firstName: "arkiv" },
          { playerId: "296", firstName: "julio" },
          { playerId: "297", firstName: "sss" },
        ],
        selected = [
          { playerId: "296", firstName: "julio" },
          { playerId: "297", firstName: "sss" },
        ],
        selectedSet = new Set(selected.map((player) => player.playerId)),
        res = all.map((player) => ({
          ...player,
          status: selectedSet.has(player.playerId),
        }));
      
      console.log(res);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-27
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        相关资源
        最近更新 更多