-3

I have a list of objects

{
  "list": {
    "item": [
      {
        "id": "12",
        "value": "abc"
      },
      {
        "id": "34",
        "value": "pqr"
      }
    ]
  }
}

and want to convert it to a map

{"12": "abc", "34","pqr"}

What is the easiest way?

I have tried iterating on each object, even Array.map(function), wanna know if there is any easier way

sidgate
  • 14,650
  • 11
  • 68
  • 119

4 Answers4

2
myObject.list.item.forEach(function(item){
  myMap[item.id] = item.value;
}

Something like this would do it...

intuitivepixel
  • 23,302
  • 3
  • 57
  • 51
1

for loop is the easiest way:

var result = {};
for (var i = 0; i < obj.list.item.length; i++) {
    result[obj.list.item[i].id] = obj.list.item[i].value;
}
console.log(result);
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

I would do something like this:

function map(list, key, value){
    var result = {};
    for(i in list){
        result[list[i][key]] = list[i][value];
    }
    return result;
}

Then with your object:

var list =  {
  "list": {
    "item": [
      {
        "id": "12",
        "value": "abc"
      },
      {
        "id": "34",
        "value": "pqr"
      }
    ]
  }
}

I could call the function like this:

map(list["list"]["item"],"id","value")

And it will return: { 12: "abc", 34: "pqr" }

Jair Reina
  • 2,606
  • 24
  • 19
0

To transform in array or a list with jsondecode in php or in c# with class with deserializate(http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net)

Andrei Chitu
  • 39
  • 1
  • 3