0

I am trying to populate a table with an array (products). My data works however it's currently putting all of the information in one row:

const products = [{
            username: JSON.stringify(data, ['from']),
            content: JSON.stringify(data, ['content']),
            date: JSON.stringify(data, ['updatedAt'])
            }]

However, I'm trying to create a for loop to make a new object for every data item. I thought I had the right concept but this isn't working at all:

const products = [
            for (let i = 0; i < data.length; i++) {
            username: JSON.stringify(data[i], ['from']),
            content: JSON.stringify(data[i], ['content']),
            date: JSON.stringify(data[i], ['updatedAt'])
            }]

Can anyone point me in the right direction?

3
  • 2
    Why isn't it just username: data.from? Why are you stringifying all the things? Commented Oct 20, 2021 at 20:22
  • 1
    You are looking for Array.prototype.map Commented Oct 20, 2021 at 20:24
  • @Andy data.from doesn't return anything, I'm fetching using an API Commented Oct 20, 2021 at 20:34

1 Answer 1

2

You can simply use map.

const products = data.map(item => ({
                username: JSON.stringify(item, ['from']),
                content: JSON.stringify(item, ['content']),
                date: JSON.stringify(item, ['updatedAt'])
               })) 

or using for loop.

let products = [];
            for (let i = 0; i < data.length; i++) {
                products.push({
                username: JSON.stringify(data[i], ['from']),
                content: JSON.stringify(data[i], ['content']),
                date: JSON.stringify(data[i], ['updatedAt'])
                }) 
            }

You can avoid stringify if not needed.


const products = data.map(item => ({
                username: item.from,
                content: item.content,
                date: item.updatedAt,
               })) 
Sign up to request clarification or add additional context in comments.

5 Comments

Hello, Writing this answer on mobile device, Editing help to format the code will be much appreciated.
This is perfect, thx a lot
No problem Wesley Bond, if this solves the problem then kindly consider accepting the answer. That'll help to mark this done.
of course, there's a time limit on how soon you can accept an answer
Gotcha, Tech Happily :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.