How to parse a json using es6? - javascript

I have below json as input
result = [
{
"category": "Social Media",
"sub_category": "Facebook"
},
{
"category": "Social Media",
"sub_category": "Instagram"
},
{
"category": "Tech",
"sub_category": "Angular"
},
{
"category": "Tech",
"sub_category": "Javascript"
}
]
i am trying to acive below json
{
"Social Media": [
"Facebook",
"Instagram"
],
"Tech": [
"Angular",
"Javascript"
]
}
Below code i tried to active this. Could anyone please help where i am doing wrong
let result = [{
"category": "Social Media",
"sub_category": "Facebook"
},
{
"category": "Social Media",
"sub_category": "Instagram"
},
{
"category": "Tech",
"sub_category": "Angular"
},
{
"category": "Tech",
"sub_category": "Javascript"
}
]
let data = [];
let categorySet = new Set();
result.forEach((val, key) => {
categorySet.add(val.category);
});
result.forEach((val, key) => {
let subCat = new Set();
categorySet.forEach((v, k) => {
if (v == val.category) {
let d = {};
d[val] = subCat.add(val.sub_category);
data.push(d)
}
})
});
console.log(data)

Your question has actually nothing to do with es6, but here is the code that could help:
const data = {}
let result = [{
"category": "Social Media",
"sub_category": "Facebook"
},
{
"category": "Social Media",
"sub_category": "Instagram"
},
{
"category": "Tech",
"sub_category": "Angular"
},
{
"category": "Tech",
"sub_category": "Javascript"
}
];
result.forEach((value) => {
data[value.category] = data[value.category] || []
data[value.category].push(value.sub_category)
});
console.log(data);
Not sure, why you wanted to use a Set, because a Set more close to an array, but what you want to get as a final result is an object

you can use lodash, try this example
result = [
{
"category": "Social Media",
"sub_category": "Facebook"
},
{
"category": "Social Media",
"sub_category": "Instagram"
},
{
"category": "Tech",
"sub_category": "Angular"
},
{
"category": "Tech",
"sub_category": "Javascript"
}
]
var groupJson= _.groupBy(result, function(result) {
return result.category;
});
console.log(groupJson);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

This would give the expected output:
let result = [{
"category": "Social Media",
"sub_category": "Facebook"
},
{
"category": "Social Media",
"sub_category": "Instagram"
},
{
"category": "Tech",
"sub_category": "Angular"
},
{
"category": "Tech",
"sub_category": "Javascript"
}
];
let data = {};
result.forEach((row) => {
if (!data[row.category]) {
data[row.category] = [];
}
if (!data[row.category].includes(row.sub_category)) {
data[row.category].push(row.sub_category);
}
});
console.log(data);

Related

Sorting array based on nested object value in javascript

I'm trying to sort/arrange array based on nested object value.
Current array :
const comments = [{
"id": 1745,
"bannerId": 35002,
"content": "lorem ipsum",
"user": "John Doe",
"banner": {
"format": "300x250",
"lang": "EN"
}
},
{
"id": 1747,
"bannerId": 35002,
"content": "test 2222",
"user": "John Doe",
"banner": {
"format": "300x250",
"lang": "EN"
}
},
{
"id": 1750,
"bannerId": 35002,
"content": "test 3333",
"user": "Frank Doe",
"banner": {
"format": "300x250",
"lang": "EN"
}
},
{
"id": 1744,
"bannerId": 35004,
"content": "bla bla",
"user": "John Doe",
"banner": {
"format": "300x600",
"lang": "EN"
}
},
{
"id": 1746,
"bannerId": 35006,
"content": "tesssttt",
"user": "Frank Doe",
"banner": {
"format": "970x250",
"lang": "NL"
}
}];
I googled many documents for sorting nested object, but I couldn't find the way of my case and I struggled so many hours so I want to ask to how can I sort above array of objects.
Desired output (or something like this) :
const comments = [{
"EN" : [{
"300x250" : [{
"John Doe" : [
{"id": 1745, "bannerId": 35002, "comment": "lorem ipsum"},
{"id": 1747, "bannerId": 35002, "comment": "test 2222"}
]
},{
"Frank Doe" : [
{"id": 1750, "bannerId": 35002, "comment": "test 3333"}
]
}]
},{
"300x600" : [{
"John Doe" : [
{"id": 1744, "bannerId": 35004, "comment": "bla bla"}
]
}]
}]
},{
"NL" : [{
"970x250" : [{
"Frank Doe" : [
{"id": 1746, "bannerId": 35006, "comment": "tesssttt"}
]
}]
}]
}];
I've already tried this without success :
let list = [];
for (let i = 0; i < comments.length; i++) {
list[comments[i].banner.lang] = [{
[comments[i].banner.format] : [{
[comments[i].user] : [{
'id': comments[i].id, 'bannerId': comments[i].bannerId, 'comments' : comments[i].content
}]
}]
}];
}
The "=" overwrite the previous data..
There is something i messed up but i can't figured out :s
Hope someone here can help me :)
You could find the nested items of the grouping arrays.
This approach takes an array of functions for getting the right key value at the wanted level.
const
data = [{ id: 1745, bannerId: 35002, content: "lorem ipsum", user: "John Doe", banner: { format: "300x250", lang: "EN" } }, { id: 1747, bannerId: 35002, content: "test 2222", user: "John Doe", banner: { format: "300x250", lang: "EN" } }, { id: 1750, bannerId: 35002, content: "test 3333", user: "Frank Doe", banner: { format: "300x250", lang: "EN" } }, { id: 1744, bannerId: 35004, content: "bla bla", user: "John Doe", banner: { format: "300x600", lang: "EN" } }, { id: 1746, bannerId: 35006, content: "tesssttt", user: "Frank Doe", banner: { format: "970x250", lang: "NL" } }],
groups = [o => o.banner.lang, o => o.banner.format, o => o.user],
result = data.reduce((r, o) => {
groups
.reduce((level, fn) => {
let key = fn(o),
p = level.find(q => key in q);
if (!p) level.push(p = { [key]: [] });
return p[key];
}, r)
.push({ id: o.id, bannerId: o.bannerId, comment: o.content });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let list = [];
for (let i = 0; i < comments.length; i++) {
if (!list[comments[i].banner.lang]) {
list[comments[i].banner.lang] = [];
}
if (!list[comments[i].banner.lang][comments[i].banner.format]) {
list[comments[i].banner.lang][comments[i].banner.format] = [];
}
if (!list[comments[i].banner.lang][comments[i].banner.format][comments[i].user]) {
list[comments[i].banner.lang][comments[i].banner.format][comments[i].user] = [];
}
list[comments[i].banner.lang][comments[i].banner.format][comments[i].user].push({
'id': comments[i].id,
'bannerId': comments[i].bannerId,
'comment' : comments[i].content
});
}

Filter an array of objects with nested arrays based on another array

I've 2 different APIs. first one returns an array of event objects (this data set is growing and expected to be large). each event has a category array that has a list of strings. The other API returns an array of filter objects. each filter has a "name" property and an array of keywords. any keyword included in the categories array in any event should go under this filter name.
The ultimate goal is to have a list of filters on the screen and when a user click on a filter I should render all events under this filter.
Event Object Example:
{
"text": {
"headline": "Headline example",
"text": "event description "
},
"media": {
"url": "https://www.google.com/",
"caption": "",
"credit": ""
},
"categories": [
"National",
"Canada",
"British Columbia"
]
}
Filters Object Example:
{
"filters": [
{
"keywords": [
"Atlantic",
"New Brunswick",
"Newfoundland and Labrador",
"Prince Edward Island",
"Nova Scotia"
],
"name": "Atlantic"
},
{
"keywords": [
"ontario",
"Quebec"
],
"name": "Central Canada"
},
{
"keywords": [
"Manitoba",
"Saskatchewan",
"Alberta"
],
"name": "Prairie Provinces"
},
{
"keywords": [
"British Columbia"
],
"name": "West Coast"
},
{
"keywords": [
"Nunavut",
"Northwest Territories",
"Yukon Territory"
],
"name": "North"
},
{
"keywords": [
"National"
],
"name": "National"
}
]
}
After a couple of days working on it I came up with this solution.
function filterTimelineData(filtersObj, timelineData) {
if (!timelineData || !filtersObj) return [];
// create a new object with filters "name" as key;
const filters = Object.keys(filtersObj);
const filteredTimelineData = Object.keys(filtersObj).reduce((o, key) => ({ ...o, [key]: [] }), {});
const filteredData = timelineData.events.reduce((acc, current) => {
let filterMatch = false;
let filterMatchName = '';
for (let i = 0; i < filters.length; i++) {
filterMatch = current.categories.some(item => {
return filtersObj[filters[i]].includes(item.toLocaleLowerCase());
});
if (filterMatch && filterMatchName !== filters[i]) { // to avoid duplicated items with different categories under the same filter
filterMatchName = filters[i];
acc[filters[i]].push(current);
}
}
return acc;
}, filteredTimelineData);
return filteredData;
}
export function timelineFiltersObj(filters) {
const filtersObj = filters.filters.reduce((acc, current) => {
const filterName = current.name.replace(/ /g, '_').toLocaleLowerCase();
if (!acc.hasOwnProperty(filterName)) {
acc[filterName] = [];
}
acc[filterName] = [].concat(current.keywords.map(item => item.toLocaleLowerCase()));
return acc;
}, {});
return filtersObj;
}
Desired output:
An object or an array for all filters to be rendered on the screen
An object with filters name as a key and the value would be an array of events that has any keyword that matches any of this filter keywords
check this code example: link
My Questions:
Is there an easier/simpler way to solve this problem?
I'm passing "filteredTimelineData" object as initial value to .reduce function. Is this legitimate? I couldn't find any answers online to this question specifically.
from a time complexity prospective. will this code cause any memory issue if the dataset grows?
This is a simple way to get the above result. I am using JavaScript ES5 features in this solution which is supported by almost all the browsers except IE9
const filters = {
"filters": [
{
"keywords": [
"Atlantic",
"New Brunswick",
"Newfoundland and Labrador",
"Prince Edward Island",
"Nova Scotia"
],
"name": "Atlantic"
},
{
"keywords": [
"ontario",
"Quebec"
],
"name": "Central Canada"
},
{
"keywords": [
"Manitoba",
"Saskatchewan",
"Alberta"
],
"name": "Prairie Provinces"
},
{
"keywords": [
"British Columbia"
],
"name": "West Coast"
},
{
"keywords": [
"Nunavut",
"Northwest Territories",
"Yukon Territory"
],
"name": "North"
},
{
"keywords": [
"National"
],
"name": "National"
}
]
};
const timelineData = {
"events": [
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"New Brunswick"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"National"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": "https://youtu.be/poOO4GN3TN4"
},
"categories": [
"Northwest Territories"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"Ontario"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"National"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": "https://philanthropy.cdn.redcross.ca/timeline/July2020-3.jpg"
},
"categories": [
"British Columbia"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"Alberta"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"Prince Edward Island"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"National"
]
},
{
"text": {
"headline": "headline example",
"text": "event-descriprion"
},
"media": {
"url": ""
},
"categories": [
"National"
]
}
]
};
var categoriesToEventsMap = timelineData.events.reduce((res, event) => {
event.categories.forEach(c=> {
res = {
...res,
[c.toLowerCase()]: [...(res[c.toLowerCase()] || []), event]
}
});
return res;
}, {})
var result = filters.filters.reduce((acc, filter) => {
let events = []
const filterName = filter.name.replace(' ', '_').toLowerCase();
filter.keywords.forEach((key)=>{
events = [...events, ...(categoriesToEventsMap[key.toLowerCase()] || [])];
});
acc[filterName] = [...(acc[filterName] || []), ...events]
return acc;
}, {});
console.log(result);

Reorder an array from a specific data

I have absolutely no idea of which title I could write.
Actually, here is what I get from API :
[
{
"order": 1,
"role": {
"label": "singer"
},
"artist": {
"name": "AaRON"
}
},
{
"order": 1,
"role": {
"label": "author"
},
"artist": {
"name": "Simon Buret"
}
},
{
"order": 2,
"role": {
"label": "author"
},
"artist": {
"name": "Olivier Coursier"
}
},
{
"order": 1,
"role": {
"label": "composer"
},
"artist": {
"name": "John Doe"
}
}
]
And here is what I need to send :
"artist": {
"singer": [
"AaRON"
],
"author": [
"Simon Buret",
"Olivier Coursier"
]
}
Of course, the order property must be taken in account.
Example : Simon Buret is the first item because he has the order set to 1.
I have absolutely no idea how to implement that, I just did a map, but don't know what to put inside :/
this.artistControl.controls.map(artistControl => {
...
});
Is there a way to do what I need ?
Does this work for you:
let arr = [
{ "order": 1, "role": { "label": "singer" }, "artist": { "name": "AaRON" } },
{ "order": 1, "role": { "label": "author" }, "artist": { "name": "Simon Buret" } },
{ "order": 2, "role": { "label": "author" }, "artist": { "name": "Olivier Coursier" } },
{ "order": 1, "role": { "label": "composer" }, "artist": { "name": "John Doe" } }
];
let obj = {'artist': {}};
arr.forEach(a => {
obj['artist'][a.role.label] = obj['artist'][a.role.label] || [];
obj['artist'][a.role.label][a.order-1] = a.artist.name;
});
console.log(obj);
You could use reduce method with object as a accumulator param and then check if the key doesn't exist create it with empty array as value and then add names by order.
const data = [{"order":1,"role":{"label":"singer"},"artist":{"name":"AaRON"}},{"order":1,"role":{"label":"author"},"artist":{"name":"Simon Buret"}},{"order":2,"role":{"label":"author"},"artist":{"name":"Olivier Coursier"}},{"order":1,"role":{"label":"composer"},"artist":{"name":"John Doe"}}]
const result = data.reduce((r, {
role: { label },
artist: { name },
order
}) => {
if (name) {
if (!r[label]) r[label] = [];
r[label][order - 1] = name;
}
return r;
}, {})
console.log(result)
const array = [{"order":1,"role":{"label":"singer"},"artist":{"name":"AaRON"}},{"order":1,"role":{"label":"author"},"artist":{"name":"Simon Buret"}},{"order":2,"role":{"label":"author"},"artist":{"name":"Olivier Coursier"}},{"order":1,"role":{"label":"composer"},"artist":{"name":"John Doe"}}];
const result = array
.sort((item1, item2) => item1.order - item2.order)
.reduce((acc, { role, artist }) => ({
...acc,
artist: {
...acc.artist,
[role.label]: [
...(acc.artist[role.label] || []),
artist.name,
],
},
}), { artist: {} });
console.log(result);
Here is another approach with es5
const data = [{ "order": 1, "role": { "label": "singer" }, "artist": { "name": "AaRON" } }, { "order": 1, "role": { "label": "author" }, "artist": { "name": "Simon Buret" } }, { "order": 2, "role": { "label": "author" }, "artist": { "name": "Olivier Coursier" } }, { "order": 1, "role": { "label": "composer" }, "artist": { "name": "John Doe" } }];
var result = data.reduce(function(map, obj) {
map["artist"] = map["artist"] || {};
if (obj.role.label === 'author' || obj.role.label === 'singer') {
map["artist"][obj.role.label] = map["artist"][obj.role.label] || [];
map["artist"][obj.role.label][obj.order - 1] = obj.artist.name;
}
return map;
}, {});
console.log(result)

Sub-grouping array of objects inside of sub-array of main array

I have an array like this
[
{
"id": 1,
"name": "Personal Information",
"TabFields": [
{
"name": "First Name",
"field": {
"code": "personFirstName"
}
},
{
"name": "Gender",
"field": {
"code": "personGenderD"
}
},
{
"name": "Last Name",
"field": {
"code": "personLastName"
}
},
{
"name": "Mobile Number",
"field": {
"code": "mobileNumber"
}
},
{
"name": "Email Address",
"field": {
"code": "emailAddress"
}
}
]
}
]
What I need is to group the objects inside the TabFields to their respective TAB (PERSONAL_INFORMATION, CONTACT_DETAILS) by code value inside the field object
The object
"name": "First Name",
"field": {
"code": "personFirstName"
}
"name": "Gender",
"field": {
"code": "personGenderD"
}
"name": "Last Name",
"field": {
"code": "personLastName"
}
is belong to PERSONAL_INFORMATION and the object
"name": "Mobile Number",
"field": {
"code": "mobileNumber"
}
"name": "Email Address",
"field": {
"code": "emailAddress"
}
is belong to CONTACT_DETAILS. So the output would be
[
{
"id": 1,
"name": "Personal Information",
"TabFields": [
{
"label": "PERSONAL_INFORMATION",
"code": "PERSONAL_INFORMATION",
"fields": [
{
"name": "First Name",
"field": {
"code": "personFirstName"
}
},
{
"name": "Gender",
"field": {
"code": "personGenderD"
}
},
{
"name": "Last Name",
"field": {
"code": "personLastName"
}
}
]
},
{
"label": "CONTACT_DETAILS",
"code": "PERSONAL_INFORMATION",
"fields": [
{
"name": "Mobile Number",
"field": {
"code": "mobileNumber"
}
},
{
"name": "Email Address",
"field": {
"code": "emailAddress"
}
}
]
}
]
}
]
How to do it in javascript?
You can also do this with map:
var arr=[ { "id": 1, "name": "Personal Information", "TabFields": [ { "name": "First Name", "field": { "code": "personFirstName" } }, { "name": "Gender", "field": { "code": "personGenderD" } }, { "name": "Last Name", "field": { "code": "personLastName" } }, { "name": "Mobile Number", "field": { "code": "mobileNumber" } }, { "name": "Email Address", "field": { "code": "emailAddress" } } ] }];
personalContact = ["Mobile Number", "Email Address"];
result = arr.map(val=>{
personalInfo = { label:'personal', code:val.name, fields:val.TabFields.filter(k=>!personalContact.includes(k.name))};
contactInfo = { label:'contact', code:val.name, fields:val.TabFields.filter(k=>personalContact.includes(k.name))};
val.TabFields = [personalInfo, contactInfo];
return val;
});
console.log(result);
Idea would be to have an array which should distinguish between the contact details and personal details using which you can apply filter to get the data.
You can express transformations simply with a library I created, rubico.
const { pipe, fork, assign, get, map, filter } = require('rubico')
const PERSONAL_INFORMATION_FIELDS = new Set(['First Name', 'Gender', 'Last Name'])
const CONTACT_DETAILS_FIELDS = new Set(['Mobile Number', 'Email Address'])
// [datum] => [datum_with_grouped_TabFields]
const groupTabFields = assign({ // reassign TabFields to new grouped TabFields
TabFields: fork([
fork({
label: () => 'PERSONAL_INFORMATION',
code: () => 'PERSONAL_INFORMATION',
fields: pipe([
get('TabFields'), // datum => datum.TabFields
filter(pipe([ // FILTER: for each TabField of TabFields
get('name'), // TabField => TabField.name
field => PERSONAL_INFORMATION_FIELDS.has(field), // check if PERSONAL_INFORMATION_FIELDS has name
])),
]),
}),
fork({ // same as above but with contact details
label: () => 'CONTACT_DETAILS',
code: () => 'CONTACT_DETAILS',
fields: pipe([
get('TabFields'),
filter(pipe([
get('name'),
field => CONTACT_DETAILS_FIELDS.has(field)
])),
]),
}),
]),
})
x = map(groupTabFields)(data)
console.log(JSON.stringify(x, null, 2)) // output is what you wanted
I've added some comments, but for a deeper understanding of the library and code I've given you, I recommend reading the intuition and then reading the docs

Iterate and group the objects using map function

Check for the decimal id and group them accordingly.
Below are the sample and recommended JSON's
Sample JSON
{
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
}
Would like to iterate and Re-structure the above JSON into below recommended format.
Logic: Should check the id(with and without decimals) and group them based on the number.
For Example:
1, 1.1, 1.2.3, 1.4.5 => data1: [{id: 1},{id: 1.1}....]
2, 2.3, 2.3.4 => data2: [{id: 2},{id: 2.3}....]
3, 3.1 => data3: [{id: 3},{id: 3.1}]
Recommended JSON
{
"results": [
{
"data1": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
}
]
},
{
"data2": [
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
}
]
},
{
"data3": [
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
}
]
},
{
"data4": [
{
"name": "Download",
"id": "4.2"
}
]
}
]
}
I have tried the below solution but it doesn't group the object
var formatedJSON = [];
results.map(function(d,i) {
formatedJSON.push({
[data+i]: d
})
});
Thanks in advance.
You can use reduce like this. The idea is to create a key-value pair for each data1, data2 etc so that values in this object are the values you need in the final array. Then use Object.values to get those as an array.
const sampleJson = {"results":[{"name":"Download","id":"1.1.1"},{"name":"Download","id":"1.2"},{"name":"Download","id":"1.3.2"},{"name":"Download","id":"2"},{"name":"Download","id":"2.3"},{"name":"Download","id":"3.2"},{"name":"Download","id":"3.5"},{"name":"Download","id":"4.2"}]}
const grouped = sampleJson.results.reduce((a, v) => {
const key = `data${parseInt(v.id)}`;
(a[key] = a[key] || {[key]: []})[key].push(v);
return a;
},{});
console.log({results: Object.values(grouped)})
One liner / Code-golf:
let s={"results":[{"name":"Download","id":"1.1.1"},{"name":"Download","id":"1.2"},{"name":"Download","id":"1.3.2"},{"name":"Download","id":"2"},{"name":"Download","id":"2.3"},{"name":"Download","id":"3.2"},{"name":"Download","id":"3.5"},{"name":"Download","id":"4.2"}]},k;
console.log({results:Object.values(s.results.reduce((a,v)=>(k=`data${parseInt(v.id)}`,(a[k] = a[k]||{[k]:[]})[k].push(v),a),{}))})
Here you go:
var data = {
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
};
let newSet = new Set();
data.results.forEach(e => {
let key = e.id.substring(0, e.id.indexOf('.'));
console.log(key);
if (newSet.has(key) == false) {
newSet.add(key);
newSet[key] = [];
}
newSet[key].push(e.id);
});
console.log(newSet);
Here's how you'd do it:
var data = {
"results": [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
};
var newData = {
"results": {}
};
data.results.forEach(item => {
var num = item.id.slice(0, 1);
if (newData.results["data" + num]) {
newData.results["data" + num].push(item);
} else {
newData.results["data" + num] = [item];
}
})
data = newData;
console.log(data);
What this does is it iterates through each item in results, gets the number at the front of this item's id, and checks if an array of the name data-{num} exists. If the array exists, it's pushed. If it doesn't exist, it's created with the item.
let input = getInput();
let output = input.reduce((acc, curr)=>{
let {id} = curr;
let majorVersion = 'name' + id.split('.')[0];
if(!acc[majorVersion]) acc[majorVersion]= [];
acc[majorVersion].push(curr);
return acc;
},{})
console.log(output)
function getInput(){
return [
{
"name": "Download",
"id": "1.1.1"
},
{
"name": "Download",
"id": "1.2"
},
{
"name": "Download",
"id": "1.3.2"
},
{
"name": "Download",
"id": "2"
},
{
"name": "Download",
"id": "2.3"
},
{
"name": "Download",
"id": "3.2"
},
{
"name": "Download",
"id": "3.5"
},
{
"name": "Download",
"id": "4.2"
}
]
}
One solution with RegEx for finer control as it would differentiate easily between 1 and 11.
Also this will make sure that even if the same version comes in end(say 1.9 in end) it will put it back in data1.
let newArr2 = ({ results }) =>
results.reduce((acc, item) => {
let key = "data" + /^(\d+)\.?.*/.exec(item.id)[1];
let found = acc.find(i => key in i);
found ? found[key].push(item) : acc.push({ [key]: [item] });
return acc;
}, []);

Categories