简体   繁体   English

如何访问'key'对象reactJS的对象属性

[英]How to access object properties of 'key' object reactJS

Would like to output this JSON data想输出这个 JSON 数据

I am struggling to find a way to output this data which I am pulling from Firebase, mostly in that I do not know how to select the objects within the 'date' object.我正在努力寻找一种方法来输出我从 Firebase 中提取的数据,主要是因为我不知道如何选择“日期”对象中的对象。 Firebase generates these keys automatically: -LMgzJGM78f0BHbPf8cc . Firebase 自动生成这些密钥: -LMgzJGM78f0BHbPf8cc

I am not able to output the properties of the objects named as above^ I have tried using nested for(in) loops.我无法输出如上命名的对象的属性^ 我尝试使用嵌套的for(in)循环。

Here is the code I am using currently:这是我目前使用的代码:

To pull the data from the database从数据库中拉取数据

 componentDidMount() {
    axios.get('./tasks.json')
      .then(response => {
        const fetchedTasks = [];
        for (let date in response.data) {
          fetchedTasks.push({
            ...response.data[date],
            date: date,
          });
          for (let item in response.data[date]) {
            fetchedTasks.push({
              ...response.data[date[item]],
              id: item
            })
          }
        }
        this.setState((prevState, props) => {
          return {
            taskList: fetchedTasks,
            loading: false
          }
        })
      })
      .catch(error => console.log(error));
  }

Mapping the state to a JSX element, only outputs like props.name :将状态映射到 JSX 元素,仅输出类似props.name

  {this.state.taskList.map((array, index) => (
            <CompleteTask
              key={array.date}
              taskName={array.date}
            />
          ) )
        }

Here is an example the data as a JSON file, it is set to the state in my app:这是将数据作为 JSON 文件的示例,它在我的应用程序中设置为状态:

{
  "tasks" : {
    "09182018" : {
      "-LMgzJGM78f0BHbPf8cc" : {
        "hours" : 0,
        "end" : "2018-09-18T14:02:25.022Z",
        "minutes" : 0,
        "name" : "sadflkjdsalkf",
        "seconds" : 2,
        "start" : "2018-09-18T14:02:22.508Z"
      },
      "-LMgzaEYe0tcCjpxOuPU" : {
        "hours" : 0,
        "end" : "2018-09-18T14:03:38.635Z",
        "minutes" : 0,
        "name" : "safd",
        "seconds" : 2,
        "start" : "2018-09-18T14:03:36.353Z"
      }
    },
  }
}

The properties of the key elements -LMgzaEYe0tcCjpxOuPU I am unsure of how to access, these data are created by another part in my app, should I move to a more shallow state to output the properties of 'hours','name', mintutes etc. or is there a way to access it as it is now?关键元素的属性-LMgzaEYe0tcCjpxOuPU我不确定如何访问,这些数据是由我的应用程序中的另一部分创建的,如果我移动到更浅的状态以输出“小时”、“名称”、分钟等属性. 或者有没有办法像现在一样访问它?

Many thanks in advance.提前谢谢了。

Are you asking how to access properties with problematic names like -LMgzJGM78f0BHbPf8cc ? 您是否在询问如何访问具有问题名称的属性,例如-LMgzJGM78f0BHbPf8cc

If so, instead of the object.property notation, you can access object properties by the property name using the square brackets syntax: 如果是这样,您可以使用方括号语法通过属性名称访问对象属性,而不是object.property表示法:

 let obj = { color: 'blue' } let prop = 'color' console.log(obj.color); console.log(obj['color']); console.log(obj[prop]); 

If not, please try to make more clear what your current problem is. 如果没有,请尝试更清楚地了解您当前的问题。

Since the keys in those objects are unknown, it may be useful to use Object.keys() . 由于这些对象中的键是未知的,因此使用Object.keys()可能很有用。 Try something like this in your JSX: 在JSX中尝试这样的事情:

Given: 鉴于:

const data = {
  "tasks" : {
    "09182018" : {
      "-LMgzJGM78f0BHbPf8cc" : {
        "name" : "Task One",
      },
      "-LMgzaEYe0tcCjpxOuPU" : {
        "name" : "Task Two",
      }
    },
  }
};

JSX: JSX:

<ul>
    {Object.keys(data.tasks).map((date) => {
        const dayTasks = tasks[date];
        return Object.keys(dayTasks).map((key) => {
            const task = dayTasks[key];
            return (
              <li>{task.name}</li>
            )
        })
    })}
</ul>

I'd suggest to transform the object received from the Firebase to array in this way: 我建议以这种方式将从Firebase接收的对象转换为数组:

const formattedTasks = [];

const tasks = Object.values(data.tasks);

tasks.forEach(task =>
  Object.entries(task).forEach(([key, value]) =>
    formattedTasks.push({ name: key, data: value })
  )
);

So, you'll map through formattedTasks array. 因此,您将映射到formattedTasks数组。

Here's a working example: https://codesandbox.io/s/l348nnkv9q 这是一个有效的例子: https//codesandbox.io/s/l348nnkv9q

 <div> { Object.entries(slot).map(([key, value]) => <div> {console.log("key", key)} <span>{key}</span> <div> {value.map(g => ( <div>{console.log("g", g.eTime)} <span>{g.eTime}</span> </div> ))} </div> </div> ) } </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM