如何访问对象键中有空格的 JavaScript 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8317982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:32:24  来源:igfitidea点击:

How can I access a JavaScript object which has spaces in the object's key?

javascriptobject

提问by julio

I have a JavaScript object that looks something like this:

我有一个看起来像这样的 JavaScript 对象:

var myTextOptions = {
  'cartoon': {
     comic: 'Calvin & Hobbes',
     published: '1993'
  },
  'character names': {
    kid: 'Calvin',
    tiger: 'Hobbes'
  }
}

I can access the properties of cartooneasily using myTextOptions.cartoon.comicor whatever. However, I haven't been able to get the syntax right for accessing kid. I've tried the following with no luck:

我可以访问cartoon轻松使用的属性myTextOptions.cartoon.comic或其他任何属性。但是,我无法获得正确的语法来访问kid. 我试过以下没有运气:

myTextOptions.character names.kid
myTextOptions."character names".kid
myTextOptions.character\ names.kid
myTextOptions.'character names'.kid
myTextOptions.["character names"].kid
myTextOptions.character%20names.kid

回答by jAndy

Use ECMAscripts "bracket notation":

使用 ECMAscripts 的“括号符号”:

myTextOptions[ 'character names' ].kid;

You can use that notation either way, reading & writting.

您可以以任何一种方式使用该符号,阅读和写作。

For more information read out here:

有关更多信息,请阅读此处:

回答by Ahmad Awais

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

JavaScript 对象的属性也可以使用括号表示法访问或设置(有关更多详细信息,请参阅属性访问器)。对象有时称为关联数组,因为每个属性都与可用于访问它的字符串值相关联。因此,例如,您可以按如下方式访问 myCar 对象的属性:

myCar['make'] = 'Ford';
myCar['model'] = 'Mustang';
myCar['year'] = 1969;

For more, read on at Working with JS Objects.

有关更多信息,请继续阅读使用 JS 对象

So in your case it's myTextOptions['character names'].kid;

所以在你的情况下 myTextOptions['character names'].kid;

回答by Shubham AK

We can also do this by -

我们也可以通过 -

myTextOptions[ 'character names' ]['kid'];

myTextOptions[ 'character names' ]['kid'];

This is useful when we have consecutive keys which consist of space.

当我们有由空格组成的连续键时,这很有用。

回答by Simon Suh

In Google Chrome, if you go to inspect element and then hover over the json file data sets, each individual data set will have a tooltip appear showing it's path and it also gives you the option to copy the path into your clipboard. Just an FYI.

在谷歌浏览器中,如果你去检查元素,然后将鼠标悬停在 json 文件数据集上,每个单独的数据集都会出现一个工具提示,显示它的路径,它还提供了将路径复制到剪贴板的选项。仅供参考。

回答by Vikas Gupta

Let me share my problem and solution here I am using VueJs with type script.

让我在这里分享我的问题和解决方案,我正在使用带有类型脚本的 VueJs。

I got following json to parse and display in UI

我得到了以下 json 来解析并显示在 UI 中

 {
    "Brand": "MAMA",
    "Variety": "Instant Noodles Coconut Milk Flavour",
    "Style": "Pack",
    "Country": "Myanmar",
    "Stars": 5,
    "Top Ten": "2016 #10"
  },

I have created the following model interfere in Typescript

我在打字稿中创建了以下模型干扰

export interface Resto {
    Brand: string;
    Variety: string;
    Style: string;
    Country: string;
    Stars: any;
    Top_Ten: string;
    }

I have called the API as:

我将 API 称为:

   public async getListOfRestos() {
    return (await fetch(
      `http://starlord.hackerearth.com/TopRamen`,
      {
        method: "get",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
        body: undefined
      }
    )) as IFetchResponse<Resto[]>;
  } 

Used in JSX like:

在 JSX 中使用,如:

 <div class="parent" v-for="(x,i) in listOfRestos" :key="i">
      <div>{{x.Brand}}</div>
      <div>{{x.Variety}}</div>
      <div>{{x.Style}}</div>
      <div>{{x.Country}}</div>
      <div>{{x.Stars}}</div>
      <div>{{x['Top Ten']}}</div>
  </div>

Same can also work in React and Angular.

同样也适用于 React 和 Angular。