Related
I'm banging my head on this problem and would appreciate some directions.
I need to select the element with the highest currentSeason.endDate for each competition.id that are the same.
Input:
[
{
"competition": {
"id": 2015,
},
"currentSeason": {
"id": 177, "endDate": "2019-05-25",
},
"id": "5b8e6ba74178bc111c9b649e"
},
{
"competition": {
"id": 2015,
},
"currentSeason": {
"id": 499, "endDate": "2020-05-31",
},
"id": "5d4191576a32da53f0a57c70"
},
{
"competition": {
"id": 2084,
},
"currentSeason": {
"id": 508, "endDate": "2020-05-30",
},
"id": "5d42bad89dd17c0ffccff9f8"
},
{
"competition": {
"id": 2013,
},
"currentSeason": {
"id": 589, "endDate": "2020-12-06",
},
"id": "5e622421bcd3fd22b4b372df"
},
{
"competition": {
"id": 2015,
},
"currentSeason": {
"id": 596, "endDate": "2021-05-23",1
},
"id": "5f16bd18da7e443c44cb7ca5"
},
{
"competition": {
"id": 2084,
},
"currentSeason": {
"id": 603, "endDate": "2021-05-30",
},
"id": "5f16bd76da7e443c44cb7ca7"
},
{
"competition": {
"id": 2011,
},
"currentSeason": {
"id": 473, "endDate": "2020-07-04",
},
"id": "5d42ba929dd17c0ffccff9f7"
},
]
Desired output:
[
{
"competition": {
"id": 2013,
},
"currentSeason": {
"id": 589, "endDate": "2020-12-06",
},
"id": "5e622421bcd3fd22b4b372df"
},
{
"competition": {
"id": 2015,
},
"currentSeason": {
"id": 596, "endDate": "2021-05-23",1
},
"id": "5f16bd18da7e443c44cb7ca5"
},
{
"competition": {
"id": 2084,
},
"currentSeason": {
"id": 603, "endDate": "2021-05-30",
},
"id": "5f16bd76da7e443c44cb7ca7"
},
{
"competition": {
"id": 2011,
},
"currentSeason": {
"id": 473, "endDate": "2020-07-04",
},
"id": "5d42ba929dd17c0ffccff9f7"
},
]
The closest i got is two nested foreach but for some reason there are still some duplicates:
competitions.forEach((c, i1) => {
competitions.forEach((n, i2) => {
if (c.competition.id === n.competition.id && c.id !== n.id) {
const cEndDate = new Date(c.currentSeason.endDate);
const nEndDate = new Date(n.currentSeason.endDate);
if (cEndDate < nEndDate) {
competitions.splice(i1, 1);
} else {
competitions.splice(i2, 1);
}
}
});
});
splice since to be reindexing the array's length but since i got those nested foreach there might be some issue there.
I also sense that the filter method could be of use with the orginal array being passed as parameter but got stuck on the logic.
Thanks in advance.
Here's a codepen for testing: https://codepen.io/kevinch/pen/dyMPdww
The most straight-forward way to do this would be to reduce the competitions inside of a map and return the values.
Just compare the current and previous dates, keeping the later one.
const latestCompDateById = (data) => {
return [...data.reduce((idMap, curr) => {
let prev = idMap.get(curr.competition.id);
if (prev != null) {
let prevDate = new Date(prev.currentSeason.endDate),
currDate = new Date(curr.currentSeason.endDate);
if (currDate > prevDate) {
idMap.set(curr.competition.id, curr);
}
} else {
idMap.set(curr.competition.id, curr);
}
return idMap;
}, new Map()).values()];
}
console.log(latestCompDateById(getData()));
function getData() {
return [{
"competition": {
"id": 2015
},
"currentSeason": {
"id": 177,
"endDate": "2019-05-25"
},
"id": "5b8e6ba74178bc111c9b649e"
}, {
"competition": {
"id": 2015
},
"currentSeason": {
"id": 499,
"endDate": "2020-05-31"
},
"id": "5d4191576a32da53f0a57c70"
}, {
"competition": {
"id": 2084
},
"currentSeason": {
"id": 508,
"endDate": "2020-05-30"
},
"id": "5d42bad89dd17c0ffccff9f8"
}, {
"competition": {
"id": 2013
},
"currentSeason": {
"id": 589,
"endDate": "2020-12-06"
},
"id": "5e622421bcd3fd22b4b372df"
}, {
"competition": {
"id": 2015
},
"currentSeason": {
"id": 596,
"endDate": "2021-05-23"
},
"id": "5f16bd18da7e443c44cb7ca5"
}, {
"competition": {
"id": 2084
},
"currentSeason": {
"id": 603,
"endDate": "2021-05-30"
},
"id": "5f16bd76da7e443c44cb7ca7"
}, {
"competition": {
"id": 2011
},
"currentSeason": {
"id": 473,
"endDate": "2020-07-04"
},
"id": "5d42ba929dd17c0ffccff9f7"
}];
}
.as-console-wrapper { top: 0; max-height: 100% !important }
Reusability
If you want a more robust and generic version, you can try this.
It allows you to:
Specify what to key on
How you compare
Optionally sort by keys
const groupReduce = (data, config) => {
const opts = {
keyFn: (item) => item.id,
cmpFn: (curr, prev) => curr - prev > 0,
sort: false,
...config
};
const result = [...data.reduce((idMap, curr) => {
const key = opts.keyFn(curr), prev = idMap.get(key);
if (prev != null) {
if (opts.cmpFn(curr, prev)) idMap.set(key, curr)
} else idMap.set(key, curr);
return idMap;
}, new Map()).values()];
return opts.sort ? result.sort((left, right) => {
return opts.keyFn(left) - opts.keyFn(right);
}) : result;
}
console.log(groupReduce(getData(), {
keyFn: (item) => item.competition.id,
cmpFn: (curr, prev) => {
const currDate = new Date(curr.currentSeason.endDate),
prevDate = new Date(prev.currentSeason.endDate);
return currDate - prevDate > 0;
},
sort: true
}));
function getData() {
return [{
"competition": {
"id": 2015
},
"currentSeason": {
"id": 177,
"endDate": "2019-05-25"
},
"id": "5b8e6ba74178bc111c9b649e"
}, {
"competition": {
"id": 2015
},
"currentSeason": {
"id": 499,
"endDate": "2020-05-31"
},
"id": "5d4191576a32da53f0a57c70"
}, {
"competition": {
"id": 2084
},
"currentSeason": {
"id": 508,
"endDate": "2020-05-30"
},
"id": "5d42bad89dd17c0ffccff9f8"
}, {
"competition": {
"id": 2013
},
"currentSeason": {
"id": 589,
"endDate": "2020-12-06"
},
"id": "5e622421bcd3fd22b4b372df"
}, {
"competition": {
"id": 2015
},
"currentSeason": {
"id": 596,
"endDate": "2021-05-23"
},
"id": "5f16bd18da7e443c44cb7ca5"
}, {
"competition": {
"id": 2084
},
"currentSeason": {
"id": 603,
"endDate": "2021-05-30"
},
"id": "5f16bd76da7e443c44cb7ca7"
}, {
"competition": {
"id": 2011
},
"currentSeason": {
"id": 473,
"endDate": "2020-07-04"
},
"id": "5d42ba929dd17c0ffccff9f7"
}];
}
.as-console-wrapper { top: 0; max-height: 100% !important }
You should be able to use Array.reduce to transform the data to the desired shape.
If the entry under competition.id is empty or has an older end date, replace it.
let data = [ { "competition": { "id": 2015, }, "currentSeason": { "id": 177, "endDate": "2019-05-25", }, "id": "5b8e6ba74178bc111c9b649e" }, { "competition": { "id": 2015, }, "currentSeason": { "id": 499, "endDate": "2020-05-31", }, "id": "5d4191576a32da53f0a57c70" }, { "competition": { "id": 2084, }, "currentSeason": { "id": 508, "endDate": "2020-05-30", }, "id": "5d42bad89dd17c0ffccff9f8" }, { "competition": { "id": 2013, }, "currentSeason": { "id": 589, "endDate": "2020-12-06", }, "id": "5e622421bcd3fd22b4b372df" }, { "competition": { "id": 2015, }, "currentSeason": { "id": 596, "endDate": "2021-05-23", }, "id": "5f16bd18da7e443c44cb7ca5" }, { "competition": { "id": 2084, }, "currentSeason": { "id": 603, "endDate": "2021-05-30", }, "id": "5f16bd76da7e443c44cb7ca7" }, { "competition": { "id": 2011, }, "currentSeason": { "id": 473, "endDate": "2020-07-04", }, "id": "5d42ba929dd17c0ffccff9f7" },]
let result = data.reduce((output, el) => {
let latestEntryIndex = output.findIndex(r => r.competition.id === el.competition.id);
if (latestEntryIndex < 0) {
// There is no entry for the given competition, add it.
output.push(el)
} else if (output[latestEntryIndex].currentSeason.endDate < el.currentSeason.endDate) {
// The entry has an older endDate, replace it
output[latestEntryIndex] = el;
}
return output;
}, []);
console.log("Result:", result);
This issue can be solved with 2 steps.
Group your objects by competition id.
Get the object with the highest current season end date from each group.
const objects = [{"competition":{"id":2015},"currentSeason":{"id":177,"endDate":"2019-05-25"},"id":"5b8e6ba74178bc111c9b649e"},{"competition":{"id":2015},"currentSeason":{"id":499,"endDate":"2020-05-31"},"id":"5d4191576a32da53f0a57c70"},{"competition":{"id":2084},"currentSeason":{"id":508,"endDate":"2020-05-30"},"id":"5d42bad89dd17c0ffccff9f8"},{"competition":{"id":2013},"currentSeason":{"id":589,"endDate":"2020-12-06"},"id":"5e622421bcd3fd22b4b372df"},{"competition":{"id":2015},"currentSeason":{"id":596,"endDate":"2021-05-23"},"id":"5f16bd18da7e443c44cb7ca5"},{"competition":{"id":2084},"currentSeason":{"id":603,"endDate":"2021-05-30"},"id":"5f16bd76da7e443c44cb7ca7"},{"competition":{"id":2011},"currentSeason":{"id":473,"endDate":"2020-07-04"},"id":"5d42ba929dd17c0ffccff9f7"}];
const groupedObjects = groupBy(objects, obj => obj.competition.id);
const chunkedObjects = Array.from(groupedObjects.values());
const maxObjects = chunkedObjects.map(chunk => (
maxBy(chunk, obj => obj.currentSeason.endDate)
));
console.log(maxObjects);
function groupBy(iterable, keyFn) {
const groups = new Map();
for (const value of iterable) {
const key = keyFn(value);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(value);
}
return groups;
}
function maxBy(iterable, keyFn) {
const iterator = iterable[Symbol.iterator]();
const {done, value} = iterator.next();
if (done) return;
let max = {key: keyFn(value), value};
for (const value of iterator) {
const key = keyFn(value);
if (key > max.key) max = {key, value};
}
return max.value;
}
I have json data format given below. From this data I need to display group11 emotions only in 3D charts.So i need x ,y and z value.how to get these values please give me some logic.we can use anything from this given json.
JSON
{
"status": "success",
"result": {
"duration": "15034.88",
"sessionStatus": "Done",
"analysisSegments": [
{
"offset": 0,
"duration": 10000,
"end": 10000,
"analysis": {
"Temper": {
"Value": "62.00",
"Group": "medium",
"Score": "59.00"
},
"Valence": {
"Value": "96.00",
"Group": "positive",
"Score": "94.00"
},
"Arousal": {
"Value": "98.00",
"Group": "high",
"Score": "97.00"
},
"Vad": {
"Voiced": "70.00"
},
"Mood": {
"Group7": {
"Primary": {
"Id": 1,
"Phrase": "Angry"
},
"Secondary": {
"Id": 3,
"Phrase": "Enthusiastic"
}
},
"Group11": {
"Primary": {
"Id": 11,
"Phrase": "Supremacy, Arrogance"
},
"Secondary": {
"Id": 1,
"Phrase": "Creative, Passionate"
}
},
"Group21": {
"Primary": {
"Id": 9,
"Phrase": "egoism"
},
"Secondary": {
"Id": 18,
"Phrase": "motivation"
}
},
"Composite": {
"Primary": {
"Id": 143,
"Phrase": "Insistence and stubbornness. Possibly childishness."
},
"Secondary": {
"Id": 5,
"Phrase": "Ambitious. Assertiveness to achieve goals."
}
}
}
}
},
{
"offset": 5000,
"duration": 10000,
"end": 15000,
"analysis": {
"Temper": {
"Value": "63.00",
"Group": "medium",
"Score": "57.00"
},
"Valence": {
"Value": "89.00",
"Group": "positive",
"Score": "84.00"
},
"Arousal": {
"Value": "94.00",
"Group": "high",
"Score": "91.00"
},
"Vad": {
"Voiced": "62.00"
},
"Mood": {
"Group7": {
"Primary": {
"Id": 1,
"Phrase": "Angry"
},
"Secondary": {
"Id": 3,
"Phrase": "Enthusiastic"
}
},
"Group11": {
"Primary": {
"Id": 11,
"Phrase": "Supremacy, Arrogance"
},
"Secondary": {
"Id": 6,
"Phrase": "Leadership, Charisma"
}
},
"Group21": {
"Primary": {
"Id": 8,
"Phrase": "dominance"
},
"Secondary": {
"Id": 18,
"Phrase": "motivation"
}
},
"Composite": {
"Primary": {
"Id": 107,
"Phrase": "Possessiveness. Ownership. Authoritative."
},
"Secondary": {
"Id": 41,
"Phrase": "Strong drive."
}
}
}
}
}
],
"analysisSummary": {
"AnalysisResult": {
"Temper": {
"Mode": "medium",
"ModePct": "100.00"
},
"Valence": {
"Mode": "positive",
"ModePct": "100.00"
},
"Arousal": {
"Mode": "high",
"ModePct": "100.00"
}
}
}
}
}
What I have tried
x-Emotion name(Supremacy, Arrogance)
y-Emotion count(how many times repeated)
z-Emotion duration(in minutes)
json parse
var counter4=0;
var val4 =0;
var val4minute =0;
var phrase = rawdata[i]["analysis"]["Mood"]["Group11"]["Primary"]["Phrase"];
if (phrase == "Supremacy, Arrogance") {
counter4++;
val4 = counter4 * 10000;
val4minute = Math.floor(val4 / 60000);
}
Here x is "Supremacy, Arrogance" counter4 is y axis and val4minute is z axis
but this logic is wrong can any one give me a better logic.
Following code gets the result below in a way that multiple iterations required. I wonder what would be the way to make it happen in a single or less iterations. Thanks in advance.
var input = [{
"ActiveMembers": [{
"Id": 101,
"Name": "alpha"
}, {
"Id": 102,
"Name": "bravo"
}],
"Contents": [{
"Id": 2001,
"RowId": "517",
"Time": "19 Jan 2017",
"ViewCount": 1124
}, {
"Id": 2002,
"RowId": "518",
"Time": "Today, 07:02 PM",
"ViewCount": 62
}],
"TotalUsers": 3,
"UsersDetails": "2 members, 1 anonymous users"
}, {
"ActiveMembers": [{
"Id": 101,
"Name": "alpha"
}, {
"Id": 103,
"Name": "charlie"
}, {
"Id": 104,
"Name": "delta"
}, {
"Id": 105,
"Name": "bravo"
}],
"Contents": [{
"Id": 2002,
"RowId": "519",
"Time": "27 Jun 2017",
"ViewCount": 4833
}, {
"Id": 2041,
"RowId": "525",
"Time": "17 Feb 2015",
"ViewCount": 24491
}],
"TotalUsers": 23,
"UsersDetails": "4 members, 19 anonymous users"
}];
var contents = Array.prototype.concat.apply([], input.map(i => i.Contents));
var activeMembers = _.uniqBy(Array.prototype.concat.apply([], input.map(i => i.ActiveMembers)), (i) => i.Id);
var totalUsers = number = _.sumBy(input, (i) => i.TotalUsers);
var userDetails = string = input.map(i => i.UsersDetails).join(' ; ');
const result = new Object();
result.Contents = contents;
result.ActiveMembers = activeMembers;
result.TotalUsers = totalUsers;
result.UserDetails = userDetails;
console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Result
{
"ActiveMembers": [
{
"Id": 101,
"Name": "alpha"
},
{
"Id": 102,
"Name": "bravo"
},
{
"Id": 103,
"Name": "charlie"
},
{
"Id": 104,
"Name": "delta"
},
{
"Id": 105,
"Name": "bravo"
}
],
"Contents": [
{
"Id": 2001,
"RowId": "517",
"Time": "19 Jan 2017",
"ViewCount": 1124
},
{
"Id": 2002,
"RowId": "518",
"Time": "Today, 07:02 PM",
"ViewCount": 62
},
{
"Id": 2002,
"RowId": "519",
"Time": "27 Jun 2017",
"ViewCount": 4833
},
{
"Id": 2041,
"RowId": "525",
"Time": "17 Feb 2015",
"ViewCount": 24491
}
],
"TotalUsers": 26,
"UsersDetails": "2 members, 1 anonymous users;4 members, 19 anonymous users"
}
Aggregate the data in a single iteration.
let ActiveMembers = [];
let Contents = [];
let TotalUsers = 0;
let UserDetails = [];
input.forEach((item) => {
ActiveMembers = ActiveMembers.concat(item.ActiveMembers);
Contents = Contents.concat(item.Contents);
TotalUsers += item.TotalUsers;
UserDetails.push(item.UsersDetails);
});
const result = {
ActiveMembers: _.uniqBy(ActiveMembers, "Id"),
Contents: Contents,
TotalUsers: TotalUsers,
UserDetails: UserDetails.join(";")
};
console.log(JSON.stringify(result));
I want to filter the items array objects which match the "model" key in the models array and store them in an array. I did succeed in my attempt but I am not very satisfied with my effort. Are there any better ways of doing it?
Any suggestions on how to do it using underscore.js and lodash? Or using the native javascript map and filter functions?
The JSON object
{
"items": [
{
"model": "ooc0d",
"code": "2x4qr",
"price": 33
},
{
"model": "ruie9",
"code": "2f6gi",
"price": 22
},
{
"model": "aqu0d",
"code": "2f6gi",
"price": 21
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 25
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 29
}
],
"models": [
{
"model": "ruie9",
"year": 1998
},
{
"model": "ooc0d",
"year": 1991
},
{
"model": "aqu0d",
"year": 1994
},
{
"model": "ddebd",
"year": 1995
},
{
"model": "odq76",
"year": 1999
}
]
}
My Solution
const { models, items } = jsonData;
const newarray = [];
for(let i = 0; i < models.length; i++) {
for(let j = 0; j < items.length; j++) {
if(items[j].model===models[i].model) {
let obj = {
...items[j],
year: models[i].year
}
newarray.push(obj);
}
}
}
I would take a slightly different approach. I guess you might like it.
const models = [
{
"model": "ruie9",
"year": 1998
},
{
"model": "not-found",
"year": 1991
},
{
"model": "aqu0d",
"year": 1994
},
{
"model": "ddebd",
"year": 1995
},
{
"model": "odq76",
"year": 1999
}
];
const items = [
{
"model": "ooc0d",
"code": "2x4qr",
"price": 33
},
{
"model": "ruie9",
"code": "2f6gi",
"price": 22
},
{
"model": "aqu0d",
"code": "2f6gi",
"price": 21
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 25
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 29
}
];
const transformed = models.reduce((res, val) => {
res[val.model] = val;
return res;
}, {}); // Transform models into a dictionary.
const filtered = items.filter(i => i.model in transformed);
console.log(filtered);
You could do this:
I thought you wanted to add the year from models array too.
If so, look at this implementation. This is more efficient O(n) than O(n*n) solution that you attempted earlier. For large arrays O(n*n) is not preferred.
let items = [{
"model": "ooc0d",
"code": "2x4qr",
"price": 33
},
{
"model": "ruie9",
"code": "2f6gi",
"price": 22
},
{
"model": "aqu0d",
"code": "2f6gi",
"price": 21
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 25
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 29
}
];
let models = [
{
"model": "ruie9",
"year": 1998
},
{
"model": "ooc0d",
"year": 1991
},
{
"model": "aqu0d",
"year": 1994
}
];
let objModels = models.reduce(function(r,v) {
r[v.model] = v;
return r;
}, {});
let objItems = items.reduce(function(r,v) {
r[v.model] = v;
return r;
}, {});
let ans = [];
for(let key in objItems) {
if(key in objModels) {
let o = objItems[key];
o.year = objModels[key].year;
ans.push(o);
}
}
console.log(ans);
You can rewrite
let obj = {
...items[j],
year: models[i].year
}
as
let obj = Object.assign({}, items[j], { year: models[i].year });
And you can also use Array.prototype.forEach instead of a for loop, like so
models.forEach((m) => {
items.forEach((i) => {
if (m.id === i.id) {
let obj = Object.assign({}, i, { year: m.year });
newArray.push(obj);
}
})
})
I tried to keep it as similar to your solution as possible.
Try this snippet:
const jsonData = {
"items": [{
"model": "ooc0d",
"code": "2x4qr",
"price": 33
},
{
"model": "ruie9",
"code": "2f6gi",
"price": 22
},
{
"model": "aqu0d",
"code": "2f6gi",
"price": 21
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 25
},
{
"model": "ddebd",
"code": "2f6gi",
"price": 29
}
],
"models": [{
"model": "ruie9",
"year": 1998
},
{
"model": "ooc0d",
"year": 1991
},
{
"model": "aqu0d",
"year": 1994
},
{
"model": "ddebd",
"year": 1995
},
{
"model": "odq76",
"year": 1999
}
]
};
var newArray = jsonData.models.reduce(
(acc, modelData) => {
let filteredItems = jsonData.items.filter(item => item.model === modelData.model);
if (filteredItems.length) {
acc.push(...filteredItems);
}
return acc;
}, [])
console.log(newArray);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a JSON data with the following format:
activities
[
{
"id": 32,
"poi_id": 1,
"due_date": "2016-09-08T18:15:00.000Z",
"items": [
{
"id": 21,
"name": "Choluv jar : JAR",
"activity_id": 32
}
]
},
{
"id": 30,
"poi_id": 9,
"due_date": "2016-09-14T18:15:00.000Z",
"items": [
{
"id": 17,
"name": "Bourbon Family : PKT",
"activity_id": 30
},
{
"id": 18,
"name": "Choluv jar : JAR",
"activity_id": 30
}
]
},
{
"id": 29,
"poi_id": 1,
"due_date": "2016-09-27T18:15:00.000Z",
"items": [
{
"id": 16,
"name": "Choluv jar : JAR",
"activity_id": 29
}
]
}
]
I want to reformat this data using lodash or simply javascript to look like this:
/*poi_id is the key*/
"1": [{
"id": 32,
"poi_id": 1,
"due_date": "2016-09-08T18:15:00.000Z",
"items": {
/*due_date is the key*/
"2016-09-08T18:15:00.000Z": [{
"id": 21,
"name": "Choluv jar : JAR",
"activity_id": 32
}]
}
}, {
"id": 29,
"poi_id": 1,
"due_date": "2016-09-27T18:15:00.000Z",
"items": {
"2016-09-27T18:15:00.000Z": [{
"id": 16,
"name": "Choluv jar : JAR",
"activity_id": 29
}]
}
}],
"9": [{
"id": 30,
"poi_id": 9,
"due_date": "2016-09-14T18:15:00.000Z",
"items": {
"2016-09-14T18:15:00.000Z": [{
"id": 17,
"name": "Bourbon Family : PKT",
"activity_id": 30
}, {
"id": 18,
"name": "Choluv jar : JAR",
"activity_id": 30
}]
}
}]
All I want is to put the data that has the same poi_id under one collection with the key of poi_id and same for the items with same due_date.
Here's what I've done so far:
let activityArray = {};
_.forEach(activities, (activityItem) => {
if (!activityArray[activityItem.poi_id]) {
activityArray[activityItem.poi_id] = [];
}
activityArray[activityItem.poi_id].push(activityItem);
_.forEach(activityArray[activityItem.poi_id], (value, key) => {
activityArray[activityItem.poi_id][key].items.unshift(activityArray[activityItem.poi_id][key].due_date);
});
});
And this is what I got:
"1": [{
"id": 32,
"poi_id": 1,
"due_date": "2016-09-08T18:15:00.000Z",
/*unShift added due_date twice here, I want here key value pair*/
"items": [
"2016-09-08T18:15:00.000Z",
"2016-09-08T18:15:00.000Z", {
"id": 21,
"name": "Choluv jar : JAR",
"activity_id": 32
}
]
}, {
"id": 29,
"poi_id": 1,
"due_date": "2016-09-27T18:15:00.000Z",
"items": [
"2016-09-27T18:15:00.000Z", {
"id": 16,
"name": "Choluv jar : JAR",
"activity_id": 29
}
]
}],
"9": [{
"id": 30,
"poi_id": 9,
"due_date": "2016-09-14T18:15:00.000Z",
"items": [
"2016-09-14T18:15:00.000Z", {
"id": 17,
"name": "Bourbon Family : PKT",
"activity_id": 30
}, {
"id": 18,
"name": "Choluv jar : JAR",
"activity_id": 30
}
]
}]
I tried with other approaches too, but couldn't make it like the one I'm expecting.
Please guide me here.
Thanks.
A compact solution in plain Javascript with an object as hash for the items arrays.
var activities = [{ "id": 32, "poi_id": 1, "due_date": "2016-09-08T18:15:00.000Z", "items": [{ "id": 21, "name": "Choluv jar : JAR", "activity_id": 32 }] }, { "id": 30, "poi_id": 9, "due_date": "2016-09-14T18:15:00.000Z", "items": [{ "id": 17, "name": "Bourbon Family : PKT", "activity_id": 30 }, { "id": 18, "name": "Choluv jar : JAR", "activity_id": 30 }] }, { "id": 29, "poi_id": 1, "due_date": "2016-09-27T18:15:00.000Z", "items": [{ "id": 16, "name": "Choluv jar : JAR", "activity_id": 29 }] }],
hash = {},
grouped = {};
activities.forEach(a => {
hash[a.poi_id] = hash[a.poi_id] || {};
hash[a.poi_id][a.due_date] = hash[a.poi_id][a.due_date] || [];
grouped[a.poi_id] = grouped[a.poi_id] || [];
grouped[a.poi_id].push({
id: a.id,
poi_id: a.poi_id,
due_date: a.due_date,
items: { [a.due_date]: hash[a.poi_id][a.due_date] }
});
a.items.forEach(b => hash[a.poi_id][a.due_date].push(b));
});
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }