3

I have the following javascript object being returned from a WCF call, this has been serialized from a dictionary object, which removed the Key/Value properties

Object { 7="XXX", 9="YYY" }

I want to convert this javascript in to the following array, with result being

[Object { Key=7, Value="XXX"}, Object { Key=9, Value="YYY"}]

I am working with the jquery client side library.

Anyone know how I can convert the object to an array of objects with Key/Value properties?

4 Answers 4

4

Here's a reusable function that'll solve your problem:

var bad = {
  7: "XXX",
  9: "YYY"
};

function fix(input) {
  var output = [];

  for (var index in input) {
    output.push({
      "KEY": index,
      "VALUE": input[index]
    });
  }

  return output;
}

// [Object { Key=7, Value="XXX"}, Object { Key=9, Value="YYY"}]
var good = fix(bad);

console.log(good)

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like:

var output = [];

for (var key in result) {
  output.push({ Key: key, Value: result[key] });
}

Where result is your WCF result. Remember, javascript objects are essentially maps, so where I can do obj.Name, I can also do obj["Name"], and I can enumerate over the members in the map, e.g.: for (var prop in obj) { // Stuff

Comments

0
a = { "7": "XXX", "9": "YYY" }

var array = [];

for(var key in a){ array.push({key: key, value: a[key]}) }

Comments

0

With Javascript, you could take the entries of the object and map the key/value pairs.

var object = { 7: "XXX", 9: "YYY" },
    array = Object
        .entries(object)
        .map(([key, value]) => ({ [key]: value }));
        
console.log(array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.