1

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.

1
  • BTW: You don't add something to an array but to an object. Commented Mar 20, 2018 at 10:40

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You also need to verify if ctx.query is not undefined before trying to access ctx.query.country or you'll have a TypeError: Cannot read property 'country' of undefined exception. It results in if (ctx.query && ctx.query.country) { ... }.
2

The problem was that you were always re initializing it. You should set it as a property of the existing object.

Update from

periodsParam = {
    country: ctx.query.country
};

to

periodsParam.country = ctx.query.country;

Comments

1

You can also just assign the Object like this:

periodsParam = Object.assign({}, periodsParam, { country: ctx.query.country });

1 Comment

As described in the MDN web docs - Object.assign(), this method copy the values of all enumerable own properties. First, you don't need to pass the first parameter {} since you want to assign into periodsParam: Object.assign(periodsParam, { country: ctx.query.country });. Additionally, this method creates a new object and we don't need it to. Why would you create a new object to assign it to our previous variable?

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.