问题
From the below Json, I am trying to build an array as shown below.
"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"
}
]
}
]
Desired Array:
{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }
Here, there can be any number of fields in the array, but not confined to "Display Name" "UserName" and "Value". so I want to build that array dynamically.
回答1:
I assume "Issues"
is a property of an object you have.
You could use this ES6 code, using reduce
:
const result = obj.Issues.map( o =>
o.Values.reduce( (acc, {Key, Value}) =>
(acc[Key] = Value, acc), {}));
const obj = {
"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"
}
]
}
]
};
const result = obj.Issues.map( o =>
o.Values.reduce ( (acc, {Key, Value}) =>
(acc[Key] = Value, acc), {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Or in ES5 compatible code, and without the (bit obscure) comma operator:
var result = obj.Issues.map(function (o) {
return o.Values.reduce(function (acc, kv) {
acc[kv.Key] = kv.Value;
return acc;
}, {})
});
var obj = {
"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"
}
]
}
]
};
var result = obj.Issues.map(function (o) {
return o.Values.reduce (function (acc, kv) {
acc[kv.Key] = kv.Value;
return acc;
}, {})
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答2:
You have to use ajax to send:
$.ajax({
url: your url,
data: { Display Name: 'Rya', etc },
type: "post",
dataType: "json",
success: function (data) {
// what you want
});
And use this function ( if you are using C#) to recivie:
JsonConvert.SerializeObject();
来源:https://stackoverflow.com/questions/42959518/converting-json-object-in-to-array