thomas305
thomas305

Reputation: 92

Error using for loop (objects inside array)

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?

Upvotes: 0

Views: 51

Answers (1)

Mehul Thakkar
Mehul Thakkar

Reputation: 2437

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,
               })) 

Upvotes: 2

Related Questions