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

javascript - How to access object properties of 'key' object reactJS - Stack Overflow

programmeradmin0浏览0评论

Would like to output this JSON data

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 generates these keys automatically: -LMgzJGM78f0BHbPf8cc.

I am not able to output the properties of the objects named as above^ I have tried using nested for(in) loops.

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:

  {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:

{
  "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?

Many thanks in advance.

Would like to output this JSON data

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 generates these keys automatically: -LMgzJGM78f0BHbPf8cc.

I am not able to output the properties of the objects named as above^ I have tried using nested for(in) loops.

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:

  {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:

{
  "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?

Many thanks in advance.

Share Improve this question edited Sep 25, 2018 at 13:13 Frank van Puffelen 599k85 gold badges888 silver badges858 bronze badges asked Sep 25, 2018 at 12:47 J TJ T 871 gold badge1 silver badge11 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 6

Are you asking how to access properties with problematic names like -LMgzJGM78f0BHbPf8cc?

If so, instead of the object.property notation, you can access object properties by the property name using the square brackets syntax:

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.

I'd suggest to transform the object received from the Firebase to array in this way:

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.

Here's a working example: https://codesandbox.io/s/l348nnkv9q

Since the keys in those objects are unknown, it may be useful to use Object.keys(). Try something like this in your JSX:

Given:

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

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>

          <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>

发布评论

评论列表(0)

  1. 暂无评论