【问题标题】:need to get index of sub array of array by typescript?需要通过打字稿获取数组子数组的索引吗?
【发布时间】:2020-12-15 06:43:52
【问题描述】:

我有一个类似的数组

let reportData = [
    {
        ReportID: 1,
        ReportHead: 'Revenue',
        collection: 75,
        subtasks: [
            {
                ReportID: 2, ReportHead: 'Plan timeline', collection: 100, isDeleted: false,
            },
            {
                ReportID: 3, ReportHead: 'Plan budget', collection: 100, isDeleted: false,
            },
            {
                ReportID: 4, ReportHead: 'Allocate resources', collection: 100, isDeleted: false,
            },
            {
                ReportID: 5, ReportHead: 'Income complete', collection: 0, isDeleted: false,
            }
        ]
    },
    {
        ReportID: 6,
        ReportHead: 'Liabilities',
        subtasks: [
            {
                ReportID: 7, ReportHead: 'Software Specification', collection: 60, isDeleted: false,
            },
            {
                ReportID: 8, ReportHead: 'Develop prototype', collection: 100, isDeleted: false,
            },
            {
                ReportID: 9, ReportHead: 'Get approval from customer', collection: 100, isDeleted: false,
            },
        ]
    }
]

我需要从这个数组中获取索引和子数组索引。像数据'ReportID:7'这个数组索引是1,子数组索引是0,打字稿

【问题讨论】:

标签: arrays typescript sub-array


【解决方案1】:

试试这样:

const result = reportData.reduce((acc, el, idx) => {
  el.subtasks.forEach((innerEl, innerIdx) => {
    acc[innerEl.ReportID] = { arrayIdx: idx, subArrayIdx: innerIdx }
  });

  return acc;
}, {});

结果:

{
  '2': { arrayIdx: 0, subArrayIdx: 0 },
  '3': { arrayIdx: 0, subArrayIdx: 1 },
  '4': { arrayIdx: 0, subArrayIdx: 2 },
  '5': { arrayIdx: 0, subArrayIdx: 3 },
  '7': { arrayIdx: 1, subArrayIdx: 0 },
  '8': { arrayIdx: 1, subArrayIdx: 1 },
  '9': { arrayIdx: 1, subArrayIdx: 2 }
}

【讨论】:

  • 我可以得到一个特定的索引吗?像 'ReportID: 7' 并得到 arrayIdx: 1, subArrayIdx:0
  • @AbdusSalam ``` const searchReport = reportId => { for (let i = 0; i
  • 亲爱的很高兴认识你的回答。现在如何删除或更新此行?
  • const 结果 = reportData.reduce((acc, el, idx) => { el.subtasks.forEach((innerEl, innerIdx) => { if (innerEl.ReportID != 7) { acc [innerEl.ReportID] = { arrayIdx: idx, elIdx: innerIdx } } }); 返回 acc; }, {});我这样做了,但我怎样才能得到报告数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2019-02-12
  • 2011-04-10
  • 2018-08-06
  • 2018-07-03
  • 2013-10-07
  • 2010-09-25
相关资源
最近更新 更多