convert object to array of objects
I have the following javascript object being re开发者_StackOverflow中文版turned 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?
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)
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
a = { "7": "XXX", "9": "YYY" }
var array = [];
for(var key in a){ array.push({key: key, value: a[key]}) }
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);
精彩评论