Need help creating an array from an object to render data

Published

I’m converting an object into an array but typescript throws and error:

"Property ‘map’ does not exist on type ‘unknown’"

(Yes, I googled that error but nothing very clear on the web)

LIVE DEMO

In this live demo you will not see the typescript error but in my Angular app I can see it and it’s causing issues :(.

enter image description here

Does anyone know how to convert this object to the same array shown on my live demo using lodash or Javascript? Thanks a lot in advance!

This is the code:

dataObject = {
A: [
    {id: 1, name: 'Mike', lastname: 'asmith'},
    {id: 2, name: 'Mary', lastname: 'alters'},
    {id: 3, name: 'Boris', lastname: 'al'}
],
B: [
    {id: 1, name: 'Lauren', lastname: 'bmith'},
    {id: 2, name: 'Travis', lastname: 'balters'},
    {id: 3, name: 'Barn', lastname: 'bl'}
], 
...
}
  
dataObjectDisp = Object.entries(this.dataObject).reduce((prev, [key, value]) =>{
  return [...prev, ...value.map((user, index) => ({ 
    ...user, parent: key, index }))]
}, []);

This is the output that I want:

 [
  {
    "id": 1,
    "name": "Mike",
    "lastname": "asmith",
    "parent": "A",
    "index": 0
  },
  {
    "id": 2,
    "name": "Mary",
    "lastname": "alters",
    "parent": "A",
    "index": 1
  },
  ...
]

Source: Angular Questions

Published
Categorized as angular, javascript, lodash, typescript Tagged , , ,

Answers

you can iterate through objects keys and get your result this way

var dataObject = {
  A: [{
      id: 1,
      name: 'Mike',
      lastname: 'asmith'
    },
    {
      id: 2,
      name: 'Mary',
      lastname: 'alters'
    },
    {
      id: 3,
      name: 'Boris',
      lastname: 'al'
    }
  ],
  B: [{
      id: 1,
      name: 'Lauren',
      lastname: 'bmith'
    },
    {
      id: 2,
      name: 'Travis',
      lastname: 'balters'
    },
    {
      id: 3,
      name: 'Barn',
      lastname: 'bl'
    }
  ],
};

const convert = (obj) => {
  var result = [];
  for (var key in obj) {

    result = result.concat(obj[key])
  }
  return result;
}
console.log(convert(dataObject))

Elza Berge

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq