underscore.js - Javascript (Underscore), function to change javascript object -


this question has answer here:

trying change object prepare send taking array inside , turning object items in array being keys values of true.

it starts out looking -

  {"state":["saved","published"],"discipline":["marketing"]} 

so end result

  {"state":{"saved":true,"published":true},"discipline":{"marketing":true}} 

so looks @ array , changes object values of true. trying use underscore plain js work fine.

here attempt, there better way this, maybe underscore? -

 function transformoutputtofiltermodel(model) {                  var transformedobj = _.map(model, function(obj) {                     return obj.reduce(function(obj, k) {                       obj[k] = true;                       return obj;                     }, {})                 });                return transformedobj;              } 

thanks reading!

edit - sorry had marked answer wihtout realizing wasn't corret. have function -

  var transformedobj = _.map(model, function(obj) {                     return obj.reduce(function(obj, k) {                         obj[k] = true;                         return obj;                     }, {});                 }); 

this format inside object correctly, pulling off outer keys - see here : https://jsfiddle.net/d0kjctfh/3/

those outer objecst should have keys of state , discipline -

{"state":{"saved":true,"committed":false,"published":false},"discipline":{"marketing":true}}; 

thanks!

i think _.map return array not best solution. try code bellow.

var t = {"state":["saved","published"],"discipline":["marketing"]}, newobj = {};  _.each(t, function(obj, index) {         newobj[index] = {};     if(_.isarray(obj)){          var toreturn = {};         _.each(obj, function(index,item){             toreturn[index] = true;         });              newobj[index] = toreturn;     } }); console.log(newobj); 

Comments

Post a Comment

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -