indra257
indra257

Reputation: 86

Converting Json object in to array using lodash

I am trying to convert my JSON result to an array to bind it to my Kendo controls. The JSON result that I am getting is as follows.

"Issues": [
    {
        "Id": null,
        "Key": null,
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Rya"
            },
            {
                "Key": "UserName",
                "Value": "RH"
            },
            {
                "Key": "Count",
                "Value": "350"
            }
        ]
    },
    {
        "Id": null,
        "Key": null,
        "Values": [
            {
                "Key": "Display Name",
                "Value": "Mike"
            },
            {
                "Key": "UserName",
                "Value": "ML"
            },
            {
                "Key": "Count",
                "Value": "90"
            }
        ]
    }
]

The array that I needed to bind it to the Kendo control is as below.

 { "Display Name": 'Rya', "UserName" : "RH", value: 350 },
 { "Display Name": 'Mike', "UserName" : "ML", value: 90 }

i)I dont want to hardcode the strings "Display Name", "User Name", "RH". I tried v.Values[0].Key: v.Values[0].Value, but it didn't work.

ii) Also I will not know how many "key, value" pairs will be present, so I need to loop through the Values and generate the array instead of fixed

category: v.Values[0].Value, 
UserName: v.Values[1].Value,
  value: v.Values[2].Value,
.
.
.
score: v.values[n].value

Upvotes: 1

Views: 3566

Answers (1)

Chris
Chris

Reputation: 58312

If you're using ES6, you don't really need lodash in this case:

var r = json.Issues.map(v => ({ 
  category: v.Values[0].Value, 
  value: v.Values[2].Value,
}));

http://codepen.io/cjke/pen/RprJdG?editors=0010

If want to use lodash or not-ES6, then:

var r = _.map(json.Issues, function(v) { 
  return {
    category: v.Values[0].Value, 
    value: v.Values[2].Value,
  }
});

Upvotes: 3

Related Questions