Search code examples
javascriptarraysnode.jssequelize.jskoa

How to pass value into array in node


Hi Im still learning node and trying something cool with javascript nodejs. Meanwhile I got stuck when pass separate "where" sequelize statement into one. Okay, this is my current code :

var periodsParam = {};
        periodsParam = {
            delete: 'F',
            tipe: 1,
            variantid: (!ctx.params.id ? ctx.params.id : variants.id)
        };

        if (ctx.query.country) {
            periodsParam = {
                country: ctx.query.country
            };
        }

        console.log(periodsParam);

From code above, its always return { country: 'SG' } , but I want to return { delete: 'F', tipe: 1, variantid: 1, country: 'SG' }

How can I resolve that ?

Anyhelp will appreciate, thankyouu.


Solution

  • The problem is, you're using = sign with periodsParam 3 times and you end up with periodsParam returning only country, because of this lines:

    if (ctx.query.country) {
      periodsParam = {
        country: ctx.query.country
      };
    }
    

    Instead of assigning new object to periodsParam, use dot notation to add another key-value pair, like this:

    if (ctx.query && ctx.query.country) { //before accesing .country check if ctx.query is truthy
      periodsParam.country = ctx.query.country;
    }
    

    As @Paul suggested, condition should be ctx.query && ctx.query.country - it will prevent TypeError if ctx.query is undefined.