1

I need meta data of fields. like this code.

var fields =  [
  { code: 'name',     display: 'Name',             isActive: true },
  { code: 'tel',      display: 'Telephone Number', isActive: true },
  { code: 'mobile',   display: 'Mobile',           isActive: true },
  { code: 'email',    display: 'Email address',    isActive: true },
  { code: 'nickname', display: 'Nickname',         isActive: true },
];

There are many fields so I'm tired. How to write without property name? I want to a flow like next code.

var fieldsString = "
code        | display            | isActive
'name'      | 'Name'             | true
'tel'       | 'Telephone Number' | true
'mobile'    | 'Mobile'           | true
'email'     | 'Email address'    | true
'nickname'  | 'Nickname'         | true
'tel'       | 'Mobile'           | true
";

var tableData = new TableData(fieldsString);
var fields = tableData.getData();

Who knows a format for table data like above code?

1
  • In your second example all you need to do is split the string at |, set up a for loop that increments by 3, build the necessary inputs. Commented Jul 9, 2015 at 2:30

1 Answer 1

1

A two dimensional array would do the trick

var keysArray = ['code','display','isActive'];
var fieldArray = [
  ['name'    , 'Name'            , true ],
  ['tel'     , 'Telephone Number', true ],
  ['mobile'  , 'Mobile'          , true ],
  ['email'   , 'Email address'   , true ],
  ['nickname', 'Nickname'        , true ],
  ['tel'     , 'Mobile'          , true ]
];

then simply use the map function of arrays to convert to the object based representation Array.prototype.map

var fields=fieldArray.map(function (current) {
  var tempobj = {};
  for(var i=0, len=keyArray.length; i<len; i++){
    tempobj[keyArray[i]] = current[i];
  }
  return tempobj;
}

You could make this even more concise by replacing the tempobj and the for loop with a call to reduce Array.protoype.reduce

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

1 Comment

Good idea! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.