简体   繁体   English

带有数组到数组的打字稿对象

[英]Typescript object with arrays to array

I need some help solving this :)我需要一些帮助来解决这个问题:)

I want to transfer the object to an array.我想将对象传输到数组。 The expected result should be:预期的结果应该是:

result = [
  {
    id: 'test-1',
    message: 'test#1.1'
  },
  {
    id: 'test-1',
    message: 'test#1.2'
  },
  {
    id: 'test-2',
    message: 'test#2.1'
  },
  {
    id: 'test-2',
    message: 'test#2.2'
  }
]

My apparent solution is with objects.keys() and map().我明显的解决方案是使用 objects.keys() 和 map()。 Unfortunately, this does not work as desired:不幸的是,这不能按预期工作:

 mockData = { 'test-1': [ { message: 'test#1.1' }, { message: 'test#1.2' } ], 'test-2': [ { message: 'test#2.1' }, { message: 'test#2.2' } ] } const result = Object.keys(this.mockData).map((id) => { return { id, ...this.mockData[id], } }) console.log(result)

do I have to put another map() over this.mockData[id]?我是否必须在 this.mockData [id] 上放置另一个 map()? what am I doing wrong and what is best practice here (maybe reduce()?)?我做错了什么,这里的最佳做法是什么(也许是 reduce()?)?

I hope you can help me我希望你能帮帮我

To ungroup you can flatMap the Object.entries of the grouped object with a nested map() call over the grouped array elements.要取消分组,您可以使用对分组数组元素的嵌套map()调用对分组对象的flatMap进行Object.entries映射。

 const mockData = { 'test-1': [{ message: 'test#1.1' }, { message: 'test#1.2' }], 'test-2': [{ message: 'test#2.1' }, { message: 'test#2.2' }] }; const result = Object.entries(mockData).flatMap(([id, vs]) => vs.map(v => ({ id, ...v }))); console.log(result);

Or using a for...of loop if you'd rather或者如果您愿意,可以使用for...of循环

 const mockData = { 'test-1': [{ message: 'test#1.1' }, { message: 'test#1.2' }], 'test-2': [{ message: 'test#2.1' }, { message: 'test#2.2' }] }; const result = []; for (const [id, messages] of Object.entries(mockData)) { for (const message of messages) { result.push({ id, ...message }); } } console.log(result);

This will return the desire solution,这将返回期望的解决方案,

const arr = [];
Object.keys(mockData).forEach((key) => {
    mockData[key].forEach((data) => {
        arr.push({
            id: key, 
            message: data.message
        })
    })
})
Object.keys(mockData)
    .map((id) =>
      mockData[id].map((l) => {
        return { ...l, id };
      })
    )
    .flat()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM