Home > Net >  How to add new array in existing object in NodeJS
How to add new array in existing object in NodeJS

Time:02-28

I need a help to add new attribute in the existing object. In my original object if product-metadata attribute exist - then I'm adding new two additional properties prodLocation and prodTime in the existing product-metadata attribute.

If my original object doesn't contain product-metadata attribute - then I've to add product-metadata attribute with these two properties prodLocation and prodTime.

I was able to add new two properties if existing object contain product-metadata attribute but I'm having an issue when original object come without product-metadata attribute.

Can someone please help how can I add new attribute in the existing object? Appreciated your help in advance. Thanks!

Please find my code below:

function updateProduct(obj) {

    const prodLocation = {
        key: 'location',
        value: 'US'
    };

    const prodTime = {
        key: 'time',
        value: '2019-01-01T00:00:00.000Z'
    };

    if (obj.hasOwnProperty('product-metadata')) {
        const prodtMetadata = existObj['product-metadata'];
        prodtMetadata.push(prodLocation);
        prodtMetadata.push(prodTime);
        obj['product-metadata'] = prodtMetadata;
        console.log(obj);
    } else {
        console.log("no metadata");
        var metaObj = {
            'product-metadata':
                [prodLocation, prodTime]
        }
        var newArr = [obj];
        newArr.push(metaObj);
        const finalJson = JSON.stringify(newArr);
        console.log(finalJson);

    }

}

var objWithMetadata = {
    "prodVersion": "0.3",
    "prodName": "test-product",
    "prodType": "electronics",
    "id": "7b966d7e-9671-45a7-9ed3-9877f26793f9",
    "product-info": {
        "price": "2323.4"
    },
    "productDesc": "test description",
    "product-metadata": [
        {
            "key": "key-1",
            "value": "value-1"
        }
    ]
};

var objWithoutMetadata = {
    "prodVersion": "0.3",
    "prodName": "test-product",
    "prodType": "electronics",
    "id": "7b966d7e-9671-45a7-9ed3-9877f26793f9",
    "product-info": {
        "price": "2323.4"
    },
    "productDesc": "test description"
};

updateProduct(objWithoutMetadata);

Expected Output:

{
    "prodVersion": "0.3",
    "prodName": "test-product",
    "prodType": "electronics",
    "id": "7b966d7e-9671-45a7-9ed3-9877f26793f9",
    "product-info": {
        "price": "2323.4"
    },
    "productDesc": "test description",
    "product-metadata": [
        {
            "key": "location",
            "value": "US"
        },
        {
            "key": "time",
            "value": "2019-01-01T00:00:00.000Z"
        }
    ]
}

CodePudding user response:

This will add your needed property to your current object when not found:

obj["product-metadata"] = [prodLocation, prodTime];
const finalJson = JSON.stringify(obj);
  • Related