【问题标题】:Accessing multiple arrays of data with different numbers访问具有不同数字的多个数据数组
【发布时间】:2017-02-10 07:31:52
【问题描述】:

我在访问数组内的数据时遇到困难。每个数组都有自己的编号。然后里面有一个数组。我想显示数组中的name

我想像这样访问数据:

source.tag.#ANY NUMBER#.name

我希望结果如下所示:

Foo, Bar, Baz

尝试 1

InnerHTML={{__html:source.tag}}

结果:

[object Object]

尝试 2

InnerHTML={{__html:JSON.stringify(source.tag)}}

结果:

{"1":[{"name":"Foo"}],"2":[{"name":"Bar"}]}

尝试 3

InnerHTML={{__html:source.tag ? source.tag.map(item => item.name).join(', ') : ''}}

结果:没有

我的数据如下所示:

"title" : "Test item"",
"tag" : {
  "1" : [ {
    "name" : "Foo"
  },
  {
    "name" : "Bar"
  } ],
  "2" : [ {
    "name" : "Baz"
  } ]
}

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    对于数据,您需要将括号表示为property accessor,以便以数字和索引的形式访问键,例如

    source.tag[1][1].name // Bar
              ^^^         // key of tag
                 ^^^      // index    
    

    var source = { title: "Test item", tag: { 1: [{ name: "Foo" }, { name: "Bar" }], 2: [{ name: "Baz" }] } };
    
    // single access
    console.log(source.tag[1][1].name);
    
    // get all names
    Object.keys(source.tag).forEach(function (key) {
        source.tag[key].forEach(function (element) {
            console.log(element.name);
        });
    });

    【讨论】:

      【解决方案2】:

      如果我们以你为例:

      myObj = {"1":[{"name":"Foo"}],"2":[{"name":"Bar"}]};

      然后访问例如“Foo”,你需要这样做:

      console.log(myObj["1"][0].name);

      脚本将打印 Foo 作为结果。

      如果要遍历整个对象,请执行以下操作:

      for (var key in myObj) console.log(myObj[key][0].name);

      【讨论】:

      • 我不想要一个结果,我想要所有结果
      【解决方案3】:

      您提到的对象包含额外的 (") 字符。首先省略这个额外的 (") 字符。然后,您将能够控制下面提到的名称:

      class User extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            title: 'Tests item',
            "tags" : {
              "1":[{
                    "name" : "Foo"
                  },
                  {
                    "name" : "Bar"
                  }],
               "2" : [ {
                      "name" : "Baz"
                    } ]
            }
          };
        }
      

      如您所见,我在当地使用了您的数据。所以现在可以访问每个标签的名称,如下所述:

       console.log(this.state.tags["1"][0].name)
      

      真实例子请运行。

      class User extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            title: 'Tests item',
            "tags" : {
              "1":[{
                    "name" : "Foo"
                  },
                  {
                    "name" : "Bar"
                  }],
               "2" : [ {
                      "name" : "Baz"
                    } ]
            }
          };
        }
       transformTags() {
          const newTagItems = [];
          Object.keys(this.state.tags).forEach((key) => {
              this.state.tags[key].forEach((item) => {
                  newTagItems.push(item.name);
              })
          });
        return newTagItems.join(',');  
      }
        render(){
         // console.log(this.state.tags["1"][0].name)
        return (
          <div>
          <h4>{this.state.title} </h4>
          <p>{this.transformTags()}</p>
               </div>
        );
      }
      
      }
      
      ReactDOM.render(
        <User/>,
        document.getElementById('root')
      );
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
      <!DOCTYPE html>
      <html>
      <head>
      <meta name="description" content="ReactJS tags">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>JS Bin</title>
      
      </head>
      <body>
        <div id="root"></div>
      </body>
      </html>

      【讨论】:

        【解决方案4】:

        遍历 data.tag 的每个属性,这将产生一个数组,对于每个属性/数组,循环遍历每个数组元素,将该元素的 name 属性添加到不断增长的字符串中,加上一个逗号。最后,删除最后一个逗号。该代码显示了完成此操作的两种不同方法。

        const source = {
          title: "Test item",
          tag: {
            "1": [{
              "name": "Foo"
            }, {
              "name": "Bar"
            }],
            "2": [{
              "name": "Baz"
            }]
          }
        };
        
        let str1 = '';
        for (let prop in source.tag) {
          for (let elmt of source.tag[prop]) {
            str1 += elmt.name + ',';
          }
        }
        str1 = str1.slice(0, -1);
        console.log(str1);
        
        let str2 = '';
        Object.keys(source.tag).map(num => {
          str2 = source.tag[num].reduce((s, e) => s + e.name + ',', str2);
        });
        str2 = str2.slice(0, -1);
        console.log(str2);

        【讨论】:

          猜你喜欢
          • 2015-07-12
          • 2013-01-08
          • 2014-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-10
          • 2021-08-26
          • 2017-11-14
          相关资源
          最近更新 更多