I have a data array like below which needs to be a structured by using Value property with Start and End Time
[{
"Timestamp": "2021-09-30T21:38:46.7000122Z",
"Value": "496",
},
{
"Timestamp": "2021-10-01T01:08:47.4690093Z",
"Value": "496",
},
{
"Timestamp": "2021-10-02T15:38:02.5080108Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T16:30:32.3410034Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T21:45:32.7460021Z",
"Value": "207",
},
{
"Timestamp": "2021-10-02T22:38:02.5839996Z",
"Value": "413",
},
{
"Timestamp": "2021-10-02T23:30:33.3980102Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T00:23:02.7130126Z",
"Value": "413",
},
{
"Timestamp": "2021-10-03T11:47:47.8630065Z",
"Value": "413",
}]
Is there a way to compose the above array to into below format like group using Value and pick the the 1st object timestamp as Start Time and last object timestamp value as End Time like below
[{
"id": 496
"stTime": "2021-09-30T21:38:46.7000122Z"
"endTime": "2021-10-01T01:08:47.4690093Z"
},{
"id": 207
"stTime": "2021-10-02T15:38:02.5080108Z"
"endTime": "2021-10-02T21:45:32.7460021Z"
},{
"id": 413
"stTime": "2021-10-02T22:38:02.5839996Z"
"endTime": "2021-10-03T11:47:47.8630065Z"
}]
const data = [
{
Timestamp: "2021-09-30T21:38:46.7000122Z",
Value: "496",
},
{
Timestamp: "2021-10-01T01:08:47.4690093Z",
Value: "496",
},
{
Timestamp: "2021-10-02T15:38:02.5080108Z",
Value: "207",
},
{
Timestamp: "2021-10-02T16:30:32.3410034Z",
Value: "207",
},
{
Timestamp: "2021-10-02T21:45:32.7460021Z",
Value: "207",
},
{
Timestamp: "2021-10-02T22:38:02.5839996Z",
Value: "413",
},
{
Timestamp: "2021-10-02T23:30:33.3980102Z",
Value: "413",
},
{
Timestamp: "2021-10-03T00:23:02.7130126Z",
Value: "413",
},
{
Timestamp: "2021-10-03T11:47:47.8630065Z",
Value: "413",
},
];
function processTimestamps(timestamps) {
return timestamps.reduce((retval, { Timestamp, Value }) => {
const currTime = new Date(Timestamp)
const existing = retval.find(obj => obj.id === Value)
if(existing){
const startTime = new Date(existing.stTime)
const endTime = new Date(existing.endTime)
if (currTime < startTime){
existing.startTime = Timestamp
}
if (currTime > endTime){
existing.endTime = Timestamp
}
}else{
retval.push({
id: Value,
stTime: Timestamp,
endTime: Timestamp
})
}
return retval
}, []);
}
console.log(processTimestamps(data));
You can use Object.values() to extract teh values result array of Array.prototype.reduce()ing the data
Code:
const data = [{Timestamp: '2021-09-30T21:38:46.7000122Z',Value: '496',},{Timestamp: '2021-10-01T01:08:47.4690093Z',Value: '496',},{Timestamp: '2021-10-02T15:38:02.5080108Z',Value: '207',},{Timestamp: '2021-10-02T16:30:32.3410034Z',Value: '207',},{Timestamp: '2021-10-02T21:45:32.7460021Z',Value: '207',},{Timestamp: '2021-10-02T22:38:02.5839996Z',Value: '413',},{Timestamp: '2021-10-02T23:30:33.3980102Z',Value: '413',},{Timestamp: '2021-10-03T00:23:02.7130126Z',Value: '413',},{Timestamp: '2021-10-03T11:47:47.8630065Z',Value: '413'}]
const result = Object
.values(
data.reduce((a, { Value, Timestamp }) => {
a[Value] = a[Value] || {
id: +Value,
stTime: Timestamp,
}
a[Value].endTime = Timestamp
return a
}, {})
)
console.log(result)
const data = [{Timestamp: '2021-09-30T21:38:46.7000122Z',Value: '496',},{Timestamp: '2021-10-01T01:08:47.4690093Z',Value: '496',},{Timestamp: '2021-10-02T15:38:02.5080108Z',Value: '207',},{Timestamp: '2021-10-02T16:30:32.3410034Z',Value: '207',},{Timestamp: '2021-10-02T21:45:32.7460021Z',Value: '207',},{Timestamp: '2021-10-02T22:38:02.5839996Z',Value: '413',},{Timestamp: '2021-10-02T23:30:33.3980102Z',Value: '413',},{Timestamp: '2021-10-03T00:23:02.7130126Z',Value: '413',},{Timestamp: '2021-10-03T11:47:47.8630065Z',Value: '413'}]
var res = data.map(e=>e.Value).filter((e,i,a)=>a.indexOf(e)==i).map(e=>({id:e,times:time.filter(x=>x.Value==e).map(x=>x.Timestamp)}))
.map(e=>({t:e,s:new Date(e)})).sort((a,b)=>a.s-b.s > 1).map(e=>e.t)
.map(e=>({id:e.id,stTime:e.times.shift(),endTime:e.times.pop()}))
console.log(res);
Related
I Have Two Array, One is normal one where dates values are being stored
var = [
"2022-05-01",
"2022-05-02",
"2022-05-03",
"2022-05-04",
"2022-05-05",
"2022-05-06",
"2022-05-07",
"2022-05-08",
"2022-05-09",
"2022-05-10",
"2022-05-11",
"2022-05-12",
"2022-05-13",
"2022-05-14",
"2022-05-15",
"2022-05-16",
"2022-05-17",
"2022-05-18",
"2022-05-19",
"2022-05-20",
"2022-05-21",
"2022-05-22",
"2022-05-23",
"2022-05-24",
"2022-05-25",
"2022-05-26",
"2022-05-27",
"2022-05-28",
"2022-05-29",
"2022-05-30"
]
The other one is objects of Array where two objects are present
var b = [
{
"k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
"v_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
"key": "Testing",
"value": "999",
"start_date": "2022-05-06T00:00:00.000Z",
"end_date": "2022-05-06T00:00:00.000Z"
},
{
"k_id": "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
"v_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
"key": "Testing",
"value": "189",
"start_date": "2022-05-08T00:00:00.000Z",
"end_date": "2022-05-`enter code here`08T00:00:00.000Z"
}
]
My Requirement is to Convert new array into like this
[
{
"value": "",
"value_id": "",
"date": "2022-05-01"
},
{
"value": "",
"value_id": "",
"date": "2022-05-02"
},
{
"value": "",
"value_id": "",
"date": "2022-05-03"
},
{
"value": "",
"value_id": "",
"date": "2022-05-04"
},
{
"value": "",
"value_id": "",
"date": "2022-05-05"
},
{
"value": "999",
"value_id": "48138929-6848-4ffe-86ce-183c75d021b4",
"date": "2022-05-06"
},
{
"value": "",
"value_id": "",
"date": "2022-05-07"
},
{
"value": "189",
"value_id": "06c4f66f-efae-4981-bebd-6734addab4a5",
"date": "2022-05-08"
},
{
"value": "",
"value_id": "",
"date": "2022-05-09"
},
{
"value": "",
"value_id": "",
"date": "2022-05-10"
},
{
"value": "",
"value_id": "",
"date": "2022-05-11"
}
]
Like in the object 2022-06-11 data is there, so the new array will consist an object which will have properties related to that object. Similar to if the object has start_date present which is also in date array, so the new array will consist object for those info. Otherwise it will create blank object respective to date.
But I am able to come with this
[
{
"value": "999",
"value_id": "aacc1765-a1d3-43c3-8233-beae19d258e5",
"date": "2022-05-06"
},
{
"value": "189",
"value_id": "ad95cc4a-ec72-4d6e-a452-f519358f265d",
"date": "2022-05-08"
},
{
"value": "",
"date": "2022-05-03"
},
{
"value": "",
"date": "2022-05-04"
},
{
"value": "",
"date": "2022-05-05"
},
{
"value": "",
"date": "2022-05-06"
},
{
"value": "",
"date": "2022-05-07"
},
{
"value": "",
"date": "2022-05-08"
},
{
"value": "",
"date": "2022-05-09"
},
{
"value": "",
"date": "2022-05-10"
},
{
"value": "",
"date": "2022-05-11"
},
{
"value": "",
"date": "2022-05-12"
},
{
"value": "",
"date": "2022-05-13"
},
{
"value": "",
"date": "2022-05-14"
},
{
"value": "",
"date": "2022-05-15"
},
{
"value": "",
"date": "2022-05-16"
},
{
"value": "",
"date": "2022-05-17"
},
{
"value": "",
"date": "2022-05-18"
},
{
"value": "",
"date": "2022-05-19"
},
{
"value": "",
"date": "2022-05-20"
},
{
"value": "",
"date": "2022-05-21"
},
{
"value": "",
"date": "2022-05-22"
},
{
"value": "",
"date": "2022-05-23"
},
{
"value": "",
"date": "2022-05-24"
},
{
"value": "",
"date": "2022-05-25"
},
{
"value": "",
"date": "2022-05-26"
},
{
"value": "",
"date": "2022-05-27"
},
{
"value": "",
"date": "2022-05-28"
},
{
"value": "",
"date": "2022-05-29"
},
{
"value": "",
"date": "2022-05-30"
}
]
It is taking only first entry and printing and rest are coming as blank.
My Code: -
var a = {};
dateArr = [];
for (var j = 0; j < this.date_val.length; j++) {
debugger;
var b = {}
console.log(val2.value[j]);
if (val2.value.length > 0) {
const newKey = this.date_val[j];
b[newKey] = val1.data;
// if (
// moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
// this.date_val[j]
// ) {
// this.vala = val2.value[j].value;
// this.valb = val2.value[j].val_id;
// this.valc = moment(val2.value[j].start_date).format(
// "YYYY-MM-DD"
// );
// }
// if (
// moment(val2.value[j].start_date).format("YYYY-MM-DD") !=
// this.date_val[j]
// ) {
a = {
value:
val2.value[j] != undefined ? val2.value[j].value : "",
value_id:
val2.value[j] != undefined
? val2.value[j].v_id
: undefined,
date:
val2.value[j] != undefined
? moment(val2.value[j].start_date).format(
"YYYY-MM-DD"
)
: this.date_val[j],
};
// }
} else {
a = {
value: "",
value_id: undefined,
date: this.date_val[j],
};
}
dateArr.push(a);
}
this.nameArray.push({
key: val1.key,
key_val: val1.id,
date: dateArr,
});
Can someone please help me with this? Thanks in Advance.
var a = [
"2022-05-01",
"2022-05-02",
"2022-05-03",
"2022-05-04",
"2022-05-05",
"2022-05-06",
"2022-05-07",
"2022-05-08",
"2022-05-09",
"2022-05-10",
"2022-05-11",
"2022-05-12",
"2022-05-13",
"2022-05-14",
"2022-05-15",
"2022-05-16",
"2022-05-17",
"2022-05-18",
"2022-05-19",
"2022-05-20",
"2022-05-21",
"2022-05-22",
"2022-05-23",
"2022-05-24",
"2022-05-25",
"2022-05-26",
"2022-05-27",
"2022-05-28",
"2022-05-29",
"2022-05-30",
];
var b = [
{
k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
v_id: "aacc1765-a1d3-43c3-8233-beae19d258e5",
key: "Testing",
value: "999",
start_date: "2022-05-06T00:00:00.000Z",
end_date: "2022-05-06T00:00:00.000Z",
},
{
k_id: "6dcb67eb-1c8a-4239-9446-f9d8f6a68086",
v_id: "ad95cc4a-ec72-4d6e-a452-f519358f265d",
key: "Testing",
value: "189",
start_date: "2022-05-08T00:00:00.000Z",
end_date: "2022-05-08T00:00:00.000Z",
},
];
let results = a.map((dateString, idx) => {
// You'll want to parse the time, many ways
// to do this, then compare times. This is
// hardcoded to work for this exact format
let bWithMatchedIndices = b.find(
({ start_date }) => dateString === start_date.split("T")[0]
);
if (bWithMatchedIndices?.start_date.split("T")[0] === dateString) {
return {
date: dateString,
value: bWithMatchedIndices.value,
value_id: bWithMatchedIndices.v_id,
};
} else {
return {
date: dateString,
value: "",
value_id: "",
};
}
});
console.log(results);
Just loop over the dates in A and find a match in B. Then create an object with the members you need and push it to the resulting array.
interface NewItem {
date: string,
value: string,
value_id: string
}
function transform(a: any[], b: any[]): NewItem[] {
let newArray: NewItem[] = []
a.forEach(item => {
const objectFound = b.find(x => x.start_date.split('T')[0] === item)
if (objectFound) {
newArray.push({ date: item, value: objectFound.value, value_id: objectFound.v_id })
} else {
newArray.push({ date: item, value: '', value_id: '' })
}
})
return newArray
}
console.log(transform(a, b))
You might want to create interfaces for the two original objects too, but I think this should help you on your way just fine.
Here's the result in a Playground.
I'm trying to group a list by an ID then inside that new list I'm trying to group a list of values based on that id in a certain time. I've manged to group by the id. I can't figure out what I need to do to group by the duration. Any help please
const data = [
{
"name": "ted",
"id": "1",
"timestamp": 1512709024000
},
{
"name": "seth",
"id": "2",
"timestamp": 1512754631000
},
{
"name": "joe",
"id": "1",
"timestamp": 1512711000000
},
{
"name": "phil",
"id": "2",
"timestamp": 1512754583000
},
{
"name": "kane",
"id": "1",
"timestamp": 1512709065294
},
]
}
{
"result": {
"1": [
{
"duration":18273
"names": ["ted", "joe", "kane"],
"startTime": 1512709065294
}
]
}
}
my efforts so far
const d= data;
const ids= data.reduce((ids, item) => {
const id= (ids[item.id] || [])
id.push(item);
ids[item.id] = id
return ids
}, {})
console.log('visitorIds',visitorIds)
Check this out:
const data = [
{"name": "ted","id": "1","timestamp": 1512709024000},
{"name": "seth","id": "2","timestamp": 1512754631000},
{"name": "joe","id": "1","timestamp": 1512711000000},
{"name": "phil","id": "2","timestamp": 1512754583000},
{"name": "kane","id": "1","timestamp": 1512709065294},
];
const visitors = (data) => {
const groupedData = data.reduce((acc, {id, name, timestamp}) => {
acc[id] = (acc[id])
? {...acc[id], names: [...acc[id].names, name], times: [...acc[id].times, timestamp]}
: {names: [name], times: [timestamp]};
const startTime = Math.min(...acc[id].times);
const finishTime = Math.max(...acc[id].times);
const duration = finishTime - startTime;
acc[id] = {...acc[id], duration, startTime};
return acc;
}, {});
Object.values(groupedData).forEach((obj) => delete obj.times);
return groupedData;
};
console.log(visitors(data));
// {
// '1': {
// names: [ 'ted', 'joe', 'kane' ],
// duration: 1976000,
// startTime: 1512709024000
// },
// '2': {
// names: [ 'seth', 'phil' ],
// duration: 48000,
// startTime: 1512754583000
// }
// }
I am trying to get the value of "type" from the object by iterating over it. The object looks like this.
{
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
}
]
}
}
]
}
}
I am able to get the type values using this:
const table = team.table;
for (let i = 0; i < table.length; i++) {
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
However, I want to use another filter on the "list" to filter non null lists. So how can I achieve that.
You want to check Check if 'list' key exists inside a team.table JSON object
you can check by
if(table[i].hasOwnProperty('list')){
}
code is
const table = team.table;
for (let i = 0; i < table.length; i++) {
if(table[i].hasOwnProperty('list')){
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
}
1) You can get all type using flatMap and map as:
obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type))
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const types = obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type));
console.log(types);
2) Using forEach and destructuring as:
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const table = obj.team.table;
const types = [];
for (let i = 0; i < table.length; i++) {
const { list: { players } } = table[i]
players.forEach(({ awards: { type }}) => types.push(type))
}
console.log(types);
It will be cleaner to use forEach.
You will need 2 forEach due to your data structure.
But below code will:
check if awards is null
check if awards.type is null
const data = {
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
},
{
"name": "Dave",
"school": "y",
"awards": {
"type": "gold"
},
"year": 2016
}
]
}
},
{
"cityCode": 444,
"list": {
"players": [
{
"name": "James",
"school": "y",
"awards": {
"type": null
},
"year": 2016
}
]
}
},
{
"cityCode": 555,
"list": {
"players": [
{
"name": "Name 101",
"school": "y",
"awards": {
"type": "platinum"
},
"year": 2016
},
{
"name": "Name 102",
"school": "y",
"awards": {
"type": null
},
"year": 2016
},
{
"name": "Name 103",
"school": "y",
"awards": null,
"year": 2016
},
]
}
}
]
}
}
// Expanded your data with more items
const data1 = data.team.table;
let types = []
data1.forEach((item, index) => {
item.list.players.forEach((player) => {
const awards = player.awards;
if (awards !== null && awards.type !== null) {
types = [...types, awards.type];
}
})
})
// Get the list of types
console.log(types);
// Get unique list of types
let unique_types = [...new Set(types)]
console.log(unique_types);
Below I have an array of objects
var data = [{
"time": "1572024707.4763825",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}, {
"time": "1572024708.3903246",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
}]
How can I restructure it to remove the repeating id's with the oldest time
I tried to pull all the unique IDs from the array so I can loop through the data array but then the code started to get too long.
data.forEach(item => {
IDs.push(item.id);
});
var unqIDs = [...new Set(IDs)];
console.log(unqIDs);
the output should look like this
outPutShouldBe = [{
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
},{
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}
]
Create an object mapping ids to the item w/ the earliest time of those with that id:
var keydata = {};
data.forEach(item=>{
var p = keydata[item.id];
if ( !p || p.time>item.time ) {
keydata[item.id] = item;
}});
Now gather up the values in that object:
var newdata = [];
for ( var k in keydata ) {
newdata.push(keydata[k]);
}
or the more elegant (thanks, #TulioF.):
var newdata = Object.values(keydata)
Using forEach() find() filter() and filter() to decide which element to return
var data = [{"time": "1572024707.4763825","rssi": "32","id": "77777"},{"time": "1572024709.0991757","rssi": "32","id": "77777"}, {"time": "1572024704.4570136","rssi": "32","id": "555555"}, {"time": "1572024708.3903246","rssi": "32","id": "77777"}, {"time": "1572024699.7132683","rssi": "32","id": "66666"}]
let resultsArray = []
data.forEach(obj=>{
const foundObj = resultsArray.find(data => data.id === obj.id)
if(foundObj && new Date(foundObj.time) > new Date(obj.time)){
const filteredArray = resultsArray.filter(data => data.id === obj.id)
resultsArray = [...filteredArray , foundObj]
} else if (!foundObj){
resultsArray.push(obj)
}
})
console.log(resultsArray)
You coud take an object as hash table and get the values directly.
var data = [{ time: "1572024707.4763825", rssi: "32", id: "77777" }, { time: "1572024709.0991757", rssi: "32", id: "77777" }, { time: "1572024704.4570136", rssi: "32", id: "555555" }, { time: "1572024708.3903246", rssi: "32", id: "77777" }, { time: "1572024699.7132683", rssi: "32", id: "66666" }],
result = Object.values(data.reduce((r, o) => {
if (!r[o.id] || +r[o.id].time > +o.time) r[o.id] = o;
return r;
}, {}));
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
use lodash to sort the array in descending order or ascending order as per your need (desc, asc) and get the zeroth object. try something like this. filter and orderBy
var data = [{
"time": "1572024707.4763825",
"rssi": "32",
"id": "77777"
}, ....];
let idsSet = new Set();
data.map(item=> idsSet.add(item.id));
let idsArr = Array.from(idsSet);
let newArr = [];
idsArr.map(id=>{
let tempArray = data.filter(item => item.id === id);
return newArr.push((_.orderBy(tempArray, ['time'],['desc']))[0]);
} )
console.log(newArr);
console output
[ {
"time": "1572024709.0991757",
"rssi": "32",
"id": "77777"
}, {
"time": "1572024704.4570136",
"rssi": "32",
"id": "555555"
}, {
"time": "1572024699.7132683",
"rssi": "32",
"id": "66666"
}];
Here you can do something like this :
let existMap = {};
data.filter(val => {
if((val.id in existMap) && (val.time>existMap[val.id])) return;
else{
existMap[val.id] = val.time;
return true;
}
})
console.log(result)
The condition can be changed based on requirement. just want to reference for your problem.
In Javascript, I created a multidimensionnal array, but for another purpose, I need to convert it.
So my array is like this
array [
0 => {
"ulStatic": [
0 => {
"day": "2019-03-30 18:30:00"
"id": "7"
"origin": "intentions"
}
]
"ulDynamic": [
0 => {
"day": "2019-03-30 18:30:00"
"id": "275"
"origin": "obs"
}
]
"ulCreatedDynamic": []
}
1 => {
"ulStatic": [
0 => {
"day": "2019-03-31 09:30:00"
"id": "8"
"origin": "intentions"
}
]
"ulDynamic": []
"ulCreatedDynamic": []
}
2 => {
"ulStatic": []
"ulDynamic": []
"ulCreatedDynamic": [
0 => {
"day": "2019-04-03 19:30:00"
"id": "277"
"origin": "obs"
}
]
}
]
And I'm trying to have this array :
array [
0 => {
"day": "2019-03-30 18:30:00"
"elements": [
0 => {
"id": "7"
"origin": "intentions"
}
1 => {
"id": "275"
"origin": "obs"
}
]
}
1 => {
"day": "2019-03-31 09:30:00"
"elements": [
0 => {
"id": "8"
"origin": "intentions"
}
]
}
2 => {
"day": "2019-04-03 19:30:00"
"elements": [
0 => {
"id": "277"
"origin": "obs"
}
]
}
]
And I must admit that I do not know where to start. I'm looking for map(), splice(), concat(), but it's confusing for me.
Can you help me to give some advices to achieve that ?
Thank you
You could group your data by day by iterating the values of the value of the objects and their array.
var array = [{ ulStatic: [{ day: "2019-03-30 18:30:00", id: "7", origin: "intentions" }], ulDynamic: [{ day: "2019-03-30 18:30:00", id: "275", origin: "obs" }], ulCreatedDynamic: [] }, { ulStatic: [{ day: "2019-03-31 09:30:00", id: "8", origin: "intentions" }], ulDynamic: [], ulCreatedDynamic: [] }, { ulStatic: [], ulDynamic: [], ulCreatedDynamic: [{ day: "2019-04-03 19:30:00", id: "277", origin: "obs" }] }],
result = array.reduce((r, o) => {
Object
.values(o)
.forEach(a => a.forEach(({ day, id, origin }) => {
var temp = r.find(p => day === p.day);
if (!temp) r.push(temp = { day, elements: [] });
temp.elements.push({ id, origin });
}));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let originalArr = [{
ulStatic: [
{
day: '2019-03-30 18:30:00',
id: '7',
origin: 'intentions'
}
],
ulDynamic: [
{
day: '2019-03-30 18:30:00',
id: '275',
origin: 'obs'
}
],
ulCreatedDynamic: []},{ulStatic: [
{
day: '2019-03-31 09:30:00',
id: '8',
origin: 'intentions'
}
],
ulDynamic: [],
ulCreatedDynamic: []},{ ulStatic: [],
ulDynamic: [],
ulCreatedDynamic: [
{
day: '2019-04-03 19:30:00',
id: '277',
origin: 'obs'
}
]}];
let op = originalArr.map(item => {
let ulStatic = item.ulStatic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let ulDynamic = item.ulDynamic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let ulCreatedDynamic = item.ulCreatedDynamic.map(ul => {
return {
id: ul.id,
origin: ul.origin
};
});
let day;
if (ulStatic.length > 0) {
day = item.ulStatic[0].day;
} else if (ulDynamic.length > 0) {
day = item.ulDynamic[0].day;
} else if (ulCreatedDynamic.length > 0) {
day = item.ulCreatedDynamic[0].day;
}
return {
day: day,
elements: [].concat(ulStatic).concat(ulDynamic)
};
});
console.log(op);
Check this out
grouping the input by day with reduce and return the object values.
const inputAry = [{
"ulStatic": [{
"day": "2019-03-30 18:30:00",
"id": "7",
"origin": "intentions"
}],
"ulDynamic": [{
"day": "2019-03-30 18:30:00",
"id": "275",
"origin": "obs"
}],
"ulCreatedDynamic": []
},
{
"ulStatic": [{
"day": "2019-03-31 09:30:00",
"id": "8",
"origin": "intentions",
}],
"ulDynamic": [],
"ulCreatedDynamic": []
},
{
"ulStatic": [],
"ulDynamic": [],
"ulCreatedDynamic": [{
"day": "2019-04-03 19:30:00",
"id": "277",
"origin": "obs"
}]
}
];
const groupByDay = inputAry.reduce((group, statics) => {
// flattens the statics array
[].concat.apply([], Object.values(statics))
.forEach(({
day,
id,
origin
}) => {
// creates a dictionary entry with day as key, if already exist use the existing one or creates a new entry
group[day] = group[day] || {
day,
elements: []
};
// push the id and origin to elements
group[day].elements.push({
id,
origin
});
});
return group;
}, {});
const expectedResult = Object.values(groupByDay);
console.log(expectedResult);