-3

How can I access the object obj properties using a for loop?

Example:

var obj = {
        id: 1,
        description: "This space is for description",
        severity: "This is severity",
        assignedTo: "Name of the assigned person",
        status: "Issue Status "
    }

Note: I am talking about this kind of loop for (var i =0;i <= obj.length;i++), not a for ... in loop. I want to display it using document.write(). Please, no jquery, only javascript.

14
  • 1
    @Kinduser The option for Object.keys() is there so it should help the OP Commented Apr 4, 2017 at 14:51
  • 1
    for..in is only JavaScript and you can still do do document.write() Do you have a specific issue with for...in? Commented Apr 4, 2017 at 14:52
  • 2
    this dupe answer provided the use of Object.keys. it clearly states, the the result is an array with keys. then just loop through the array with for i ... Commented Apr 4, 2017 at 14:55
  • 5
    Possible duplicate of Iterate through object properties Look at this answer in the duplicate using Objects.keys()stackoverflow.com/questions/8312459/… and .foreach can easily be replaced by for i on the result of Object.keys() Commented Apr 4, 2017 at 14:57
  • 2
    @squint, maybe the main question is, how to use document.write with arguments ...? Commented Apr 4, 2017 at 15:13

1 Answer 1

2

You are able to use for loop together with Object.keys().

Note: As squint mentioned, it does not guarantee the right order.

var obj = {
  id: 1,
  description: "This space is for description",
  severity: "This is severity",
  assignedTo: "Name of the assigned person",
  status: "Issue Status "
}, elems = Object.keys(obj);

for (var i = 0; i < elems.length; i++) {
  document.write(`Key: ${elems[i]}, Value: ${obj[elems[i]]}<br>`);
}

Sign up to request clarification or add additional context in comments.

3 Comments

@squint What I mean by order is the order of keys depending on when they've been defined (or set)!
@ibrahimmahrir: Yes, the original definition order is what some may hope for, but I think Kind user's answer gave that warning. An implementation may indeed choose to honor that order, but we shouldn't rely on it.
...I actually wish that JS implementations would randomize the order so that people don't have the illusion that it may be reliable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.