How to make a foreach of an object in javascript?

11,776

Solution 1

You can use the Object.keys() method, which returns an array of the keys in an object. Then we run that through an Array.forEach() method. for example

Object.keys(lunch).forEach(function (item) {
    console.log(item); // key
    console.log(lunch[item]); // value
});

Solution 2

Your CurrentSelec variable is an array, not an ordinary object, so just use its forEach method:

CurrentSelec.forEach(function (el) {
    console.log(el.qSelected);
});
Share:
11,776
Clément Boyer
Author by

Clément Boyer

Updated on June 27, 2022

Comments

  • Clément Boyer
    Clément Boyer almost 2 years

    I am currently building a mashup in Qlik Sense in JavaScript and jQuery. I have made some data selection and I have put them in a variable object :

    var CurrentSelec = app1.selectionState().selections;
    console.log(CurrentSelec);`
    console.log(typeof CurrentSelec);
    

    This is what I get on my browser console :

    CurrentSelec Object

    I'm trying to show the qSelected value in a Foreach :

    I have tried with Javascript :

    for(var index in CurrentSelec) { 
        console.log(index.qSelected);
    }
    

    I have tried with jQuery:

    $.each(CurrentSelec, function(i, index) {
      console.log(index.qSelected)
    });
    

    But my browser console do not show the log of my foreach.

    Do you know how to properly make a foreach of an object and show its content on a browser console, please ?

    Regards.

    • Tyler Roper
      Tyler Roper almost 7 years
      CurrentSelec is not an object, it is an array. If it were an object, the first line of your image would say Object instead of Array(1), and the typeof CurrentSelect would output Object {} instead of object.
  • Tyler Roper
    Tyler Roper almost 7 years
    Consider adding some more substance to your answer. Just giving OP a code to substitute doesn't really explain much.
  • Tyler Roper
    Tyler Roper almost 7 years
  • Tyler Roper
    Tyler Roper almost 7 years
  • notphilphil
    notphilphil almost 7 years
    @Santi Ah, I neglected the fact that it is an array. However, it is still valid (as long as you iterate correctly).
  • Tyler Roper
    Tyler Roper almost 7 years
    Sure. Just figured I'd provide some food for thought.