如何转换此数组:
var users = [
{
'date':'jan',
'visits': 2,
'drops': 1
},
{
'date':'feb',
'visits': 3,
'drops': 2
}
]
进入这个数组:
var newArray = [
{
'name': 'visits',
'data': [
2, 3
]
},
{
'name': 'drops',
'data': [
1, 2
]
}
]
使用
newArray = users.map(function(){
return ...
});
谢谢!
答案 0 :(得分:1)
你可以这样减少它:
string signature;
using (var sha = SHA256.Create())
{
long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000;
Console.WriteLine("Timestamp: " + ts);
var computedHash = sha.ComputeHash(Encoding.UTF8.GetBytes(apiKey + sharedSecret + ts));
signature = BitConverter.ToString(computedHash).Replace("-", "");
}
var client = new RestClient("https://api.test.hotelbeds.com/");
var request = new RestRequest("/hotel-api/1.0/hotels", Method.POST);
var body = new TestRequest
{
stay = new Stay
{
checkIn = "2016-06-18",
checkOut = "2016-06-10",
shiftDays = "2"
},
occupancies = new Occupancy[]
{
new Occupancy
{
rooms = 1,
adults = 2, children = 1,
paxes = new Pax []
{
new Pax
{
type = "AD",
age = 30
},
new Pax
{
type = "AD",
age = 30
},
new Pax
{
type = "CH",
age = 8
}
}
}
},
geolocation = new Geolocation
{
longitude = 2.646633999999949F,
latitude = 39.57119F,
radius = 20,
unit = "km"
}
};
request.AddHeader("X-Signature", signature);
request.AddHeader("Api-Key", apiKey);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
return View();
}
答案 1 :(得分:0)
您可以使用缩小功能转换数组。这是动态的。
var users = [{
'date': 'jan',
'visits': 2,
'drops': 1
}, {
'date': 'feb',
'visits': 3,
'drops': 2
}];
function transform(data, blacklist) {
return Object.keys(data[0]).filter(function(key) {
return blacklist.indexOf(key) === -1;
}).map(function(key) {
return data.reduce(function(obj, record) {
obj.data.push(record[key]);
return obj;
}, {
name: key,
data: []
});
});
}
function print(obj) {
document.body.innerHTML = '<pre>' + JSON.stringify(obj, null, 2) + '</pre>';
}
print(transform(users, ['date']));
答案 2 :(得分:0)
只是一个更通用的解决方案。
var users = [{ 'date': 'jan', 'visits': 2, 'drops': 1 }, { 'date': 'feb', 'visits': 3, 'drops': 2 }],
result = function (data, names) {
var r = [];
data.forEach(function (a) {
names.forEach(function (b, i) {
r[i] = r[i] || { name: b, data: [] };
r[i].data.push(a[b])
});
});
return r;
}(users, ['visits', 'drops']);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');