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?
Andy
63.7k13 gold badges72 silver badges99 bronze badges
1 Answer 1
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,
}))
answered Oct 20, 2021 at 20:26
Mehul Thakkar
2,4571 gold badge16 silver badges23 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Mehul Thakkar
Hello, Writing this answer on mobile device, Editing help to format the code will be much appreciated.
thomas305
This is perfect, thx a lot
Mehul Thakkar
No problem Wesley Bond, if this solves the problem then kindly consider accepting the answer. That'll help to mark this done.
thomas305
of course, there's a time limit on how soon you can accept an answer
Mehul Thakkar
Gotcha, Tech Happily :)
lang-js
username: data.from? Why are you stringifying all the things?Array.prototype.map