最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to access JSON property with hyphen “-” in React Js(Babel) - Stack Overflow

programmeradmin1浏览0评论

I'm building a small React ponents (pile with Babel). I have to access property with a dash inside the name.

this.setState({
  newArtist: {
    birthdate: artist.life-span.begin
  }
});

This code throw an error Uncaught ReferenceError: span is not defined

After some research, I found out that I need to use a alternative notatio using bracket. ['life-span']

this.setState({
  newArtist: {
    birthdate: artist['life-span']begin
  }
});

But this one make Babel to throw a syntax error.

bundle.js:1 SyntaxError: /file/path: Unexpected token, expected , (24:38) while parsing file

So I'm stuck here.

My babel configuration is quite lite, only use the es2015 & react preset.

Any idea what it could be ?

I'm building a small React ponents (pile with Babel). I have to access property with a dash inside the name.

this.setState({
  newArtist: {
    birthdate: artist.life-span.begin
  }
});

This code throw an error Uncaught ReferenceError: span is not defined

After some research, I found out that I need to use a alternative notatio using bracket. ['life-span']

this.setState({
  newArtist: {
    birthdate: artist['life-span']begin
  }
});

But this one make Babel to throw a syntax error.

bundle.js:1 SyntaxError: /file/path: Unexpected token, expected , (24:38) while parsing file

So I'm stuck here.

My babel configuration is quite lite, only use the es2015 & react preset.

Any idea what it could be ?

Share Improve this question asked Nov 18, 2016 at 13:51 Dry-macaronyDry-macarony 676 bronze badges 2
  • 4 Add . before begin - artist['life-span'].begin – Oleksandr T. Commented Nov 18, 2016 at 13:53
  • @AlexanderT. Or for consistency: artist['life-span']['begin'] – Mr. Polywhirl Commented Nov 18, 2016 at 13:55
Add a ment  | 

2 Answers 2

Reset to default 11
birthdate: artist['life-span'].begin

instead of birthdate: artist['life-span']begin

You must understand basics like that: properties must be qouted and rounded by square brackets, or start from dot. So in properties chain:

var propNameInVar = "prop5";
object   ["prop1"]   .prop2   [3]   .prop4   [propNameInVar]   .prop6
发布评论

评论列表(0)

  1. 暂无评论