对象在模板字符串中传播

时间:2016-12-26 00:49:12

标签: javascript ecmascript-6

是否可以使用在模板字符串中传播的对象:

const obj = {
    key1: 'value1',
    key2: 'value2'
};

// contrived example to show that `obj` can also be dynamically constructed
for (let i = 0; i < 3; i++) {
    obj[`someKey${i}`] = i
}

const templateString = `{
    "templateKey1": "anotherValue1",
    "templateKey2": "anotherValue2",
    ${...obj}
}`

预期结果:

console.log(templateString)
// should output an object in string format:
'{
    "templateKey1": "anotherValue1",
    "templateKey2": "anotherValue2",
    "key1": "value1", 
    "key2": "value2",
    "someKey0": 0,
    "someKey1": 1,
    "someKey2": 2
}'

尝试编译时,我只收到Unexpected token错误消息。

我的项目正在使用babel,对象传播插件按预期工作,因此配置不正确。

2 个答案:

答案 0 :(得分:0)

是的,这是可能的。但

  • 默认情况下,对象不可迭代
  • 您必须传播到数组初始值设定项或函数调用

const obj = {
  key1: 'value1',
  key2: 'value2',
  [Symbol.iterator]: function*() {
    var indent = 4;
    yield JSON.stringify(this, null, indent).slice(2+indent, -2);
  }
};
for (let i = 0; i < 3; i++) obj[`someKey${i}`] = i;
console.log(`{
    "templateKey1": "anotherValue1",
    "templateKey2": "anotherValue2",
    ${[...obj]}
}`);
/* `{
    "templateKey1": "anotherValue1",
    "templateKey2": "anotherValue2",
    "key1": "value1",
    "key2": "value2",
    "someKey0": 0,
    "someKey1": 1,
    "someKey2": 2
}` */

答案 1 :(得分:0)

如果预期结果是原始对象,则不需要rest和spread元素来返回预期结果。使用JSON.stringify()JSON.parse()

const obj = {
    key1: 'value1',
    key2: 'value2'
};

const templateString = `${JSON.stringify(obj)}`

console.log(JSON.parse(templateString));