Search code examples
javascriptarrayssplitobject-notation

Split array into pairs and pack into object


I have a an array with CSS text declarations like this: ['display: none ', 'opacity: 0.1', ' color: #ff0000']

I want to split these into object key/value notation so it ends up like this:

{
  display: 'none',
  opacity: 0.1,
  color: '#ffffff'
}

edit: I've got a working wrong example, but it seems overly complicated and it doesnt serve the purpose (d'oh). Do you have a working one?

cssStyleDeclarations.map(function(item) {
  var x = item.split(':');
  var ret = {};
  ret[x[0].trim()] = x[1].trim();

  return ret;
});

It returns it as array with an object for each entry ([Object, Object, Object]), but I want it as a pure object.


Solution

  • Check out Array.prototype.reduce():

    var input = ['display: none ', 'opacity: 0.1', ' color: #ff0000'];
    
    var css = input.reduce((p, c) => {
      var x = c.split(':');
      p[x[0].trim()] = x[1].trim();
      return p;
    }, {});
    
    console.log(css);