MyDaftQuestions MyDaftQuestions - 1 year ago 132
Javascript Question

How to create a list from a C# Dictionary return object

My Ajax call returns a Dictionary from C#.

return = pp.Shares
.Select(c => new
}).ToDictionary(d => d.Url, d => d.Name);

The above returns a JSON object

This means my return in JavaScript looks like:

key1: value
key2: value
key3: value2

I need to pass all values as an array to another function.

Do I have to loop through all the return values and create a new array for the values to pass to the required function, or is there a simpler way?

Answer Source

The following assumes that the input is fixed and cannot be formatted e.g. as JSON.

First split your input up into lines, i.e. by \n or \r\n depending on the input. Then split the lines again into key and value and pick the values:

var input = 'key1: value\nkey2: value\nkey3: value2';

var lines = input.split('\n');
var values = {
  return line.split(': ')[1];

console.log(values); // ["value", "value", "value2"]

Edit: Since your input is already provided in JSON format, it is even easier. JSON.parse() the string and extract the object values:

var input = '{"key1":"value","key2":"value","key3":"value2"}';

var parsed = JSON.parse(input);

var values = Object.keys(parsed).map(function(key) {
  return parsed[key];

console.log(values); // ["value", "value", "value2"]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download