如何将值传递给节点中的数组

How to pass value into array in node

嗨,我还在学习 node 并尝试使用 javascript nodejs 做一些很酷的事情。 同时,当将单独的 "where" sequelize 语句合并为一个时,我被卡住了。 好的,这是我当前的代码:

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);

从上面的代码来看,它总是 return { country: 'SG' } ,但我想 return { delete: 'F', tipe: 1, variantid: 1, country: 'SG' }

我该如何解决?

任何帮助将不胜感激,谢谢。

问题是您总是重新初始化它。您应该将其设置为现有对象的 属性。

更新自

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

periodsParam.country = ctx.query.country;

您也可以像这样分配对象:

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

问题是,您使用 =periodsParam 签名 3 次,最终 periodsParam 仅返回 country,因为以下几行:

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

不是将新对象分配给 periodsParam,而是使用点符号添加另一个 key-value 对,如下所示:

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

正如 @Paul 所建议的那样,条件应该是 ctx.query && ctx.query.country - 如果 ctx.queryundefined,它将防止 TypeError。