Search code examples
javascriptjsontypescriptfunctional-programming

Build Json from an array of objects


I'm trying to use typescript to build a json object from an array of objects like this one:[

[
  { attribute: 'a', modifier: 121 },
  { attribute: 'b', modifier: 67 },
  { attribute: 'c', modifier: 121 },
  { attribute: 'd', modifier: 67 } 
]

I would like to get something like:

{
  a:  121,
  b:  67,
  c:  121,
  d:  67  
}

But I just can't get my head around the high order functions to make it work.


Solution

  • You could use reduce method which accepts as parameter a callback function.

    Read more about reduce method here.

    let array=[
      { attribute: 'a', modifier: 121 },
      { attribute: 'b', modifier: 67 },
      { attribute: 'c', modifier: 121 },
      { attribute: 'd', modifier: 67 } 
    ];
    let obj=array.reduce(function(obj,item){
      obj[item.attribute] = item.modifier;
      return obj;
    },{});
    console.log(obj);