0

I am trying to write a for loop to create a columns object like below:

columns: [
    {data: "productCode", title: "Product Code", width: "7%"},
    {data: "brand", title: "Brand", width: "10%"},
]

so far, I have tried:

Define each column attributes:

var ltColumns = {

    "col1": {data: "productCode", title: "Product Code", width: "7%" },

    "col2": {data: "brand", title: "Brand", width: "10%"}
};

Populate the column attributes with a for loop.

columns: [
        for (var key in ltColumns) {
            {
             data: ltColumns[key].data, 
             title: ltColumns[key].title, 
             width: ltColumns[key].width}
            }
         ];

However, I keep getting the error Unexpected token for. Can someone help me with the syntax?

Thanks!!

3 Answers 3

3

ES7

That syntax, also known as array comprehensions are a very new feature in version of JavaScript called ES7. If you want to use this feature (currently only firefox supports this), you can do:

columns: [
    for (i of ltColumns)
    {
        data : i.data,
        title: i.title,
        width: i.width
    }
]    

ES6

A new version of JavaScript which is actually now very well supported in popular browsers called ES6 has features which can help when doing something like this:

columns: Object.keys(ltColumns).map(item => ltColumns[item])

ES5

ES5 is the current version of JavaScript:

Method 1

You can do:

columns: Object.keys(ltColumns).map(function (item) { return
    ltColumns[item] })

Method 2

for in loops are also an option:

for (var i in ltColumns)
    columns[i] = ltColumns[i];
Sign up to request clarification or add additional context in comments.

Comments

2

You need to do the for loop outside of the array:

var columns = [];

for(var key in ltColumns) {
  columns.push({
    data: ltColumns[key].data, 
    title: ltColumns[key].title, 
    width: ltColumns[key].width
  });
}

I would suggest looking at MDN's docs on Array.prototype.

The method I used above is Array.prototype.push, which pushes an item to the end of the array.

Note: this is a common ES5 implementation.

1 Comment

Unfiltered for in loops are dangerous I'd advise against them
1
var columns = Object.keys(ltColumns).map(function (key) { return ltColumns[key]; });

Be careful, as it works slower than general solution with for in.

It always better to create helper function for common operations:

function values(obj) {
    return Object.keys(obj).map(function (e) { return obj[e]; });
}

someObject.columns = values(ltColumns);

But better to use fastest solution for helper functions.

function values(obj) {
    var result = [];

    for (var name in obj)
        if (obj.hasOwnProperty(name))
            result.push(obj[name]);

    return result;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.