【问题标题】:array filtering and map dynamically in jsjs中的数组过滤和动态映射
【发布时间】:2021-08-28 12:09:59
【问题描述】:

我有一个这样的 json:

[
  {
    "part": "LM",
    "section": "021",
    "column": "001",
    "description": "Descrizione attività/passività",
    "type": "NUM"
  },
  {
    "part": "LM",
    "section": "021",
    "column": "002",
    "description": "Assenza cause Ostative Applicazione Regime",
    "type": "CB"
  },
  {
    "part": "LM",
    "section": "042",
    "column": "001",
    "description": "Differenza su reddito",
    "type": "NUM"
  },
  {
    "part": "LM",
    "section": "050",
    "column": "006",
    "description": "Perdite non compensate - Eccedenza 2018",
    "type": "NUM"
  }
]

我想映射项目拆分为部分道具。 方面输出是:

      <div>section 021
        <p>column 001</p>
        <p>column 002</p>
      </div>

      <div>section 042
      <p>column 001</p>
      </div>

      <div>section 050
      <p>column 006</p>
      </div>

如何动态传递section prop作为过滤参数?

我尝试过类似的方法: obj.filter((item) => item.section == "021").map((item) => ... 并且可以工作,但我希望“021”对于对象中的每个值都是动态的。

非常感谢你们

【问题讨论】:

标签: javascript reactjs loops dictionary filter


【解决方案1】:
export default function App() {
  const data = [
    {
      part: 'LM',
      section: '021',
      column: '001',
      description: 'Descrizione attività/passività',
      type: 'NUM'
    },
    {
      part: 'LM',
      section: '021',
      column: '002',
      description: 'Assenza cause Ostative Applicazione Regime',
      type: 'CB'
    },
    {
      part: 'LM',
      section: '042',
      column: '001',
      description: 'Differenza su reddito',
      type: 'NUM'
    },
    {
      part: 'LM',
      section: '050',
      column: '006',
      description: 'Perdite non compensate - Eccedenza 2018',
      type: 'NUM'
    }
  ];

  const output = Object.values(
    data.reduce((b, a) => {
      if (b.hasOwnProperty(a.section)) b[a.section].columns.push(a.column);
      else {
        a.columns = [a.column];
        b[a.section] = a;
      }
      return b;
    }, {})
  );
  // console.log(output);

  return (
    <div>
      {output.map(obj => (
        <div>
          {obj.section}
          <ul>
            {obj.columns.map(col => (
              <li> {col} </li>
            ))}
          </ul>
        </div>
      ))}
    </div>
  );
}

在这里查看:https://stackblitz.com/edit/react-txmy72?file=src/App.js

【讨论】:

  • reduce 是对的,但是映射到 react 组件我需要测试
  • @sedprc - 这是一个反应组件还是只是 javascript?
  • 反应组件
  • @sedprc - 更新和可测试的@stackblitz 链接
  • 好的,但是哪个也是显示描述的正确条件?我已经以某种方式进行了修改,但第一个循环跳过了描述。结果在这里:stackblitz.com/edit/react-ja52hk?file=src/App.js
猜你喜欢
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 2016-03-27
  • 2022-01-14
  • 2017-11-13
  • 2022-01-13
相关资源
最近更新 更多