简体   繁体   中英

Accessing data in a javascript object that has the same name

I have a javascript object that looks similar to this:

var data = {
  Message: {
       sent: 'complete',
       received: true,
       time: '4:06 PM' 
   },
  Message: {
       sent: 'complete',
       received: false,
       time: '9:01 AM' 
   },
  Message {
     ...... // and so on
   }    
}

And I want to access each one of the sent , received and time objects and push them to an array.So for example, it might look like this when its done:

['complete', 'complete', 'Not complete'] // sent
[true, true, false]  // received 
['4:06 PM','9:01 AM', '2:00 PM' ] // time

I know this is pretty basic, but I'm not sure how to get every one of sent , received and time , only the last one (relatively new to js).

How can I get every one of sent , received and time ? I'm pretty sure I could figure out the array portion, however if you include it in the solution I'd really appreciate it!

You can not have two keys in an object with the same name. Instead try an array:

 var messages = [ { sent: 'complete', received: true, time: '4:06 PM' }, { sent: 'complete', received: false, time: '9:01 AM' }, { sent: 'complete', received: false, time: '1:01 PM' } ]; messages.forEach( (message) => { console.log(message.sent, message.time); } ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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