1

I've a RESTFUL WEB Service returning data in JSON format. Need to build a Map from the JSON returned by the service using AngularJS.

For instance, let the json be like as follows:

myJSON = [{
    id: 8,
    color: "red",
    value: "#f00"
},
{
    id: 37,
    color: "green",
    value: "#0f0"
},
{
    id: 45,
    color: "blue",
    value: "#00f"
}]

Need to build a map using id & value from the above JSON. I could imagine something like as follows:

var map = [myJSON.id : myJSON.value]

which would return something like

map = {8: "red", 37: "green", 45: "blue"}

A trivial solution would be looping thro' the JSON array and construct a map but is there any other method of achieving my GOAL?

0

1 Answer 1

3

Use the reduce function on array. See MDN. Note that this has nothing to do with angular. This is vanilla js.

var mapped = myJSON.reduce(function(map, field) {
    map[field.id] = field.color;
    return map;
}, {});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.