1

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!

1 Answer 1

4

Your expected output is an object, not an array. If you want that output, your code should be like this:

var jsonObj = {};

myObject.product.forEach(function (data) {
    //console.log(myObject)
    console.log(data.message)

    if (data.message.includes('123839')) {
        jsonObj.productID = data.message;
    }
    if (data.message.includes('iPhone')) {
        jsonObj.productName = data.message;
    }


});

console.log(jsonObj);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.