I'm forming JSON inside my forEach loop based on certain conditions but JSON is not forming the way I expected, please find my code below:
app.js
var myObject = {
product: [
{
timestamp: 1622650177246,
message: 'productID-123839'
},
{
timestamp: 1622650177268,
message: 'productName-iPhone'
}
]
}
var jsonArr = [];
myObject.product.forEach(function (data) {
//console.log(myObject)
console.log(data.message)
if (data.message.includes('123839')) {
jsonArr.push({ 'productID': data.message })
}
if (data.message.includes('iPhone')) {
jsonArr.push({ 'productName': data.message })
}
});
console.log(jsonArr)
I'm getting output like this:
[
{ productID: 'productID-123839' },
{ productName: 'productName-iPhone' }
]
But my expected output something like this:
{
productID: 'productID-123839',
productName: 'productName-iPhone'
}
And finally, I would like to read jsonArr.productID or jsonArr.productName
How to get something like this, any help would be much appreciated. Thanks!