4

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.

3 Answers 3

5

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);

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

Comments

2

You could use Object.assign in combination with Array#map.

var array = [{ attribute: 'a', modifier: 121 }, { attribute: 'b', modifier: 67 }, { attribute: 'c', modifier: 121 }, { attribute: 'd', modifier: 67 }],
    result = Object.assign(...array.map(o => ({ [o.attribute]: o.modifier })));

console.log(result);

With destructuring assignment

var array = [{ attribute: 'a', modifier: 121 }, { attribute: 'b', modifier: 67 }, { attribute: 'c', modifier: 121 }, { attribute: 'd', modifier: 67 }],
    result = Object.assign(...array.map(({ attribute, modifier }) => ({ [attribute]: modifier })));

console.log(result);

Comments

1

try this.

var arr = [
  { attribute: 'a', modifier: 121 },
  { attribute: 'b', modifier: 67 },
  { attribute: 'c', modifier: 121 },
  { attribute: 'd', modifier: 67 } 
]
var map = {};
arr.forEach( function(item){ map[ item.attribute ] = item.modifier });
console.log( JSON.stringify( map, 0, 4 ) )

Comments

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.