Skip to content
Advertisement

Javascript: Object.keys(myarray).forEach vs myarray.forEach((obj) => {

Is there an alternative way of looping through my array of objects? it seems the engine version on the application im using is old and doesnt support myArray.forEach((obj) => { but this works on an single object array I think. Object.keys(myArray).forEach(

{“jurisdiction”:”SCPB – LON”},{“firstName”:”David Dynamic”}

var array = []

$('input:checked').each(function() {

        var key_ = $(this).attr('name')
        var val = $(this).attr('name').val();

        var obj = {
            [key_]: val
        };
        array.push(obj);

        array.forEach((obj) => {
                    Object.keys(obj).forEach((key) => {
                            alert(key: " + key + " - value: " + obj[key]);
                            });
                    });
}); 

Error produced by the webapp

JST-310000 Error while compiling script '_webApp_APP303__preview' line 175: syntax error (line='     array.forEach((obj) => {
' token='> {
').
SCR-160032 JavaScript: error while compiling script '_webApp_APP303__preview'.

Also tried a loop to no avail.

array.forEach(obj => {
  
  for (let key in obj) {
    logInfo(`${key}: ${obj[key]}`);
  }

}); 

JST-310000 Error while compiling script ‘_webApp_APP303__preview’ line 176: syntax error (line=’array.forEach(obj => { ‘ token=’> { ‘). SCR-160032 JavaScript: error while compiling script ‘_webApp_APP303__preview’.

Advertisement

Answer

The error message you have added shows that this particular JavaScript engine does not support arrow function syntax, as it trips over the => token, already at the outer loop.

The solution is to use function callbacks only:

    array.forEach(function (obj) {
        Object.keys(obj).forEach(function (key) {
            alert("key: " + key + " - value: " + obj[key]);
        });
    });
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement