Reputation: 338
I have a big problem to format my complex object into another complex object. I get the first type of complex object from an incoming device Message. I cannot change the format of the incoming message.
I try to format my message into another complex object to use it somewhere else in my program.
Here is the format of the incoming message :
var measures = [
{
dev: "test",
usg: "IMPORT",
vals: [
{ val: 1000, date: "2019-01-01T00:00:00Z"},
{ val: 2000, date: "2019-01-02T00:00:00Z"},
{ val: 3000, date: "2019-01-03T00:00:00Z"}
]
},
{
dev: "test2",
usg: "EXPORT",
vals: [
{ val: 300, date: "2019-01-01T00:00:00Z"},
{ val: 400, date: "2019-01-02T00:00:00Z"},
{ val: 500, date: "2019-01-03T00:00:00Z"}
]
}
];
The dates are the same for the 2 measures that i get. That is perfectly normal and that is what i'm trying to use.
Now it is the expected format. Dates must be a dictionary where dates are the keys.
Dates = [
{
"2019-01-01T00:00:00Z" : {
{usg : "IMPORT", dev : "test", val : 1000 },
{usg : "EXPORT", dev : "test2" val : 300 }
},
{
"2019-01-02T00:00:00Z" : {
{ usg : "IMPORT", dev : "test", val : 2000},
{ usg : "EXPORT", dev : "test2", val : 400 }
},
{
"2019-01-03T00:00:00Z" : {
{ usg : "IMPORT", dev : "test", val : 3000},
{ usg : "EXPORT", dev : "test2", val : 500 }
}
];
I managed to get a dictionary like this :
Dates = [
{
"2019-01-01T00:00:00Z" : {
{ val : 1000 },
{ val : 300 }
},
{
"2019-01-02T00:00:00Z" : {
{ val : 2000},
{ val : 400 }
},
{
"2019-01-03T00:00:00Z" : {
{ val : 3000},
{ val : 500 }
}
];
with the following code but I cannot reach the "usg" and "dev" properties in the last part of the .map method.
var dates = measures.map(varVals => varVals.vals)
.reduce((a, b) => a.concat(b))
.map(varDates => varDates.date);
var dicoVal = {};
dates.forEach(date => dicoVal[date] =
measures.map(varVals => varVals.vals)
.reduce((a, b) => a.concat(b))
.filter(item => item.date == date)
.map(valeur => { val : valeur.val}));
I tried to get "varVals.usg" or "varVals.dev", but it's not reachable and I know why but I can't find a solution to this.
That's my problem.
Thanks for reading !
I hope you will enjoy solving my problem :D
Upvotes: 1
Views: 42
Reputation: 26844
Assuming the inner object is an array, you can use reduce
to summarize the array into an object. Use Object.values()
to convert the object into an array.
Use forEach
to loop through the array.
var measures = [{"dev":"test","usg":"IMPORT","vals":[{"val":1000,"date":"2019-01-01T00:00:00Z"},{"val":2000,"date":"2019-01-02T00:00:00Z"},{"val":3000,"date":"2019-01-03T00:00:00Z"}]},{"dev":"test2","usg":"EXPORT","vals":[{"val":300,"date":"2019-01-01T00:00:00Z"},{"val":400,"date":"2019-01-02T00:00:00Z"},{"val":500,"date":"2019-01-03T00:00:00Z"}]}];
var date = Object.values(measures.reduce((c, v) => {
v.vals.forEach(o => {
c[o.date] = c[o.date] || {[o.date]: []};
c[o.date][o.date].push({usg: v.usg,dev: v.dev,val: o.val});
})
return c;
}, {}));
console.log(date);
Upvotes: 2