将其他文件中的值对象调用为对象值

时间:2018-09-16 07:21:50

标签: javascript node.js object call

我的邮件对象包含:

const message = {
        headers: {
            i need to call another object to here
        }
};

我在另一个文件中有配置对象:

exports.custom_headers{

    'x-my-key': 'header value',
    'x-another-key': 'another value'

}

我需要用配置文件中的对象替换标头的整个名称和值

该如何引用? 我尝试直接调用对象,但没有成功

通常该对象是这样工作的

const message = {
    from: random_message.fromname+'<'+random_message.fromemail+'>',
    to: email,
    subject: random_message.subject,
    text: random_message.text,
    html: random_message.html,
    headers: {
            'x-my-key': 'header value',
            'x-another-key': 'another value'
    }
};

但是我需要将标题导出到另一个文件

2 个答案:

答案 0 :(得分:1)

如果这是您想要的。您可以使用...(扩展运算符)来扩展对象的键。

const custom_headers =  {
    'x-my-key': 'header value',
    'x-another-key': 'another value'
};

const message = {
   from: 'random_message.fromname'+'<'+'random_message.fromemail'+'>',
   to: 'email',
   subject: 'random_message.subject',
   text: 'random_message.text',
   html: 'random_message.html',
  headers:{
    ...custom_headers
  }
};

console.log(message);

答案 1 :(得分:0)

//basically you have 2 object and wants to override one object's with another

//here is one object
const message = {
        headers: {
            "old-header1": "old-header-value1",
        "common-property": "old-header-value2"
        }
};

//here is config object
const config = {
    "new-header1": "new-header-value1",

    "common-property": "new-header-value2"
};

//message.headers = {}; //uncomment this if you want to remove all older properties

//to override properties
Object.keys(config).forEach(function(d) { message.headers[d] = config[d]; });