0

I have this following object:

var d = { 
  "restaurant": 20, 
  "hotel": 40, 
  "travel": 60 
}

And I need to transform it into this:

var a = [
{ 
  "category_name": "restaurant",
  "amount": 20
},
{ 
  "category_name": "hotel",
  "amount": 40
},
{ 
  "category_name": "travel",
  "amount": 60
}
]

This might be a silly question but as I am not a programmer I am facing this issue. Could some one help me at least pointing a direction for me to follow?

1
  • 4
    note that var d = { "restaurant": 20, "hotel": 40, "hotel": 60 } will be equal to var d = { "restaurant": 20, "hotel": 60 } as there is no point of having duplicated keys in object, later one just overrides the former one Commented Apr 22, 2019 at 12:32

2 Answers 2

3

Try this

Object.keys(d).map(k=>({"category_name": k, "amount": d[k]}))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer. I just updated the question because I forgot to sum one of the values, but I will try your answer to get unstuck.
key of object is unique so your object is not correct, so you can't do operations on it, but if you want to fix it you can do something like this var d = { "restaurant": 20, "hotel": [40, 60], } @LucasRezende
I just got the proper output result that I should have put on the question description. Now that's right and thank you for the help! All the best.
0

Use map and reduce with Object.entries:

var a = Object.entries(Object.entries(d).reduce((acc, [k, v]) => {
    (acc[k] = acc[k] || 0) += parseInt(v);
    return acc;
}, {})).map(([k, v]) => ({ category_name: k, amount: v }));

4 Comments

not summing the hotel amount values
It won't since you cant have multiple same keys in object :) the question is incorrect
Oh yes, I didn't see that - therefore my first answer was correct?
Updated the question description and now that's right. Thank you for the tip.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.