0

My Ajax call returns a Dictionary from C#.

 return = pp.Shares
        .Select(c => new
        {
            c.Url,
            c.Name
        }).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?

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120

1 Answers1

3

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 = lines.map(function(line) {
  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"]
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94