LazyCubicleMonkey
LazyCubicleMonkey

Reputation: 1243

Can You Generate an Object With Property Names That Come from An Array?

Let's say I have a variable length array, such that each element of the array has some property:

var columns = [
    {
      field: 'state',
      label: 'State'
    }, {
      field: 'type',
      label: 'Type'
    }, {
      field: 'side',
      label: 'Side'
    }
]

I want to create a new object such that it will have a named property for each value of field in the array above, assigned to some value in another array (order):

row = {
                state: order[0]
                type: order[1]
                side: order[2]
}

But based on the original array, so it would be something similar to:

 row = {
                var i = 0
                for col in columns
                  row[col.field]: order[i++]
}

Is there some way to do this?

Upvotes: 0

Views: 56

Answers (2)

CD..
CD..

Reputation: 74126

Like this:

var row = {};

columns.forEach(function(column, index){
  row[column.field]  = order[index];
});

Upvotes: 3

Maurice Perry
Maurice Perry

Reputation: 32831

You nearly did it:

var row = {};
columns.forEach(function(col, index) {
    row[col.field] = order[index];
});

Upvotes: 1

Related Questions