I have a heavy array like this:
[
{Id: 1, Name: 'Red', optionName: 'Color'},
{Id: 2, Name: 'Yellow', optionName: 'Color'},
{Id: 3, Name: 'Blue', optionName: 'Color'},
{Id: 4, Name: 'Green', optionName: 'Color'},
{Id: 7, Name: 'Black', optionName: 'Color'},
{Id: 8, Name: 'S', optionName: 'Size'},
{Id: 11, Name: 'M', optionName: 'Size'},
{Id: 12, Name: 'L', optionName: 'Size'},
{Id: 13, Name: 'XL', optionName: 'Size'},
{Id: 14, Name: 'XXL', optionName: 'Size'}
]
What I need to do is to group them by optionName and have two row in the main array like this:
[
{
Name: 'Color',
Data:[{Id: 1, Name: 'Red'},
{Id: 2, Name: 'Yellow'},
{Id: 3, Name: 'Blue'},
{Id: 4, Name: 'Green'},
{Id: 7, Name: 'Black'}]
}, {
Name: 'Size',
Data:[{Id: 8, Name: 'S'},
{Id: 11, Name: 'M'},
{Id: 12, Name: 'L'},
{Id: 13, Name: 'XL'},
{Id: 14, Name: 'XXL'}]
}
]
How to do it in javascript?
This is a snippet I wrote for these kind of situations. You can add this functionality to all of your arrays:
Object.defineProperty(Array.prototype, 'group', {
enumerable: false,
value: function (key) {
var map = {};
this.forEach(function (e) {
var k = key(e);
map[k] = map[k] || [];
map[k].push(e);
});
return Object.keys(map).map(function (k) {
return {key: k, data: map[k]};
});
}
});
You can use it like this. You can just pass a function which defines how you want to group your data.
var newArray = arr.group(function (item) {
return item.optionName;
});
Working Fiddle
If you need, you can replace {key: k, data: map[k]} with {Name: k, Data: map[k]}.
This is also more compact ES6 version of the code above:
Object.defineProperty(Array.prototype, 'group', {
enumerable: false,
value: function (key) {
let map = {};
this.map(e => ({k: key(e), d: e})).forEach(e => {
map[e.k] = map[e.k] || [];
map[e.k].push(e.d);
});
return Object.keys(map).map(k => ({key: k, data: map[k]}));
}
});
Use it like this:
let newArray = arr.group(item => item.optionName))
An ES6 solution using Map object:
function groupBy(arr, key) {
return arr.reduce(
(sum, item) => {
const groupByVal = item[key];
groupedItems = sum.get(groupByVal) || [];
groupedItems.push(item);
return sum.set(groupByVal, groupedItems);
},
new Map()
);
}
var Data = [
{ Id: 1, Name: 'Red', optionName: 'Color' },
{ Id: 2, Name: 'Yellow', optionName: 'Color' },
{ Id: 3, Name: 'Blue', optionName: 'Color' },
{ Id: 4, Name: 'Green', optionName: 'Color' },
{ Id: 7, Name: 'Black', optionName: 'Color' },
{ Id: 8, Name: 'S', optionName: 'Size' },
{ Id: 11, Name: 'M', optionName: 'Size' },
{ Id: 12, Name: 'L', optionName: 'Size' },
{ Id: 13, Name: 'XL', optionName: 'Size' },
{ Id: 14, Name: 'XXL', optionName: 'Size' } ];
document.getElementById("showArray").innerHTML =JSON.stringify([...groupBy(Data, 'optionName')], null, 4);
<pre id="showArray"></pre>
You can use reduce to get the resultset you need:
var result = list.reduce(function(memo, item) {
if (item.optionName === 'Color') {
memo[0].Data.push(
Id: item.Id,
Name: item.Name
});
}
if (item.optionName === 'Size') {
memo[1].Data.push({
Id: item.Id,
Name: item.Name
});
}
return memo;
}, [{ Name: 'Color', Data: [] }, { Name: 'Size', Data: [] }]);
variable list is your first list.
Hope this helps.
This is a snippet I wrote for kind of my situation in my application functionality of all arrays. This snippet code is use in node js application. All the above is is given solution but I was finding some problem in server side in node js.
This snippet is user full me....
var Data= [
{ Id: 1, Name: 'Red', optionName: 'Color' },
{ Id: 2, Name: 'Yellow', optionName: 'Color' },
{ Id: 3, Name: 'Blue', optionName: 'Color' },
{ Id: 4, Name: 'Green', optionName: 'Color' },
{ Id: 7, Name: 'Black', optionName: 'Color' },
{ Id: 8, Name: 'S', optionName: 'Size' },
{ Id: 11, Name: 'M', optionName: 'Size' },
{ Id: 12, Name: 'L', optionName: 'Size' },
{ Id: 13, Name: 'XL', optionName: 'Size' },
{ Id: 14, Name: 'XXL', optionName: 'Size' } ];
function groupBy(arr, key) {
var newArr = [],
types = {},
newItem, i, j, cur;
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!(cur[key] in types)) {
types[cur[key]] = { type: cur[key], data: [] };
newArr.push(types[cur[key]]);
}
types[cur[key]].data.push(cur);
}
return newArr;
}
I use it like this. I just pass a function which defines how you want to group our data.
filterData= groupBy(Data,'optionName');
Result of this snippet of code output.....
[
{"type":"Color","data":[{"Id":1,"Name":"Red","optionName":"Color"},
{"Id":2,"Name":"Yellow","optionName":"Color"},
{"Id":3,"Name":"Blue","optionName":"Color"},
{"Id":4,"Name":"Green","optionName":"Color"},
{"Id":7,"Name":"Black","optionName":"Color"}]},
{"type":"Size","data":[{"Id":8,"Name":"S","optionName":"Size"},
{"Id":11,"Name":"M","optionName":"Size"},
{"Id":12,"Name":"L","optionName":"Size"},
{"Id":13,"Name":"XL","optionName":"Size"},
{"Id":14,"Name":"XXL","optionName":"Size"}]}
]
Show on fiddle
var originalList = [ { Id: 1, Name: 'Red', optionName: 'Color' },
{ Id: 2, Name: 'Yellow', optionName: 'Color' },
{ Id: 3, Name: 'Blue', optionName: 'Color' },
{ Id: 4, Name: 'Green', optionName: 'Color' },
{ Id: 7, Name: 'Black', optionName: 'Color' },
{ Id: 8, Name: 'S', optionName: 'Size' },
{ Id: 11, Name: 'M', optionName: 'Size' },
{ Id: 12, Name: 'L', optionName: 'Size' },
{ Id: 13, Name: 'XL', optionName: 'Size' },
{ Id: 14, Name: 'XXL', optionName: 'Size' } ];
var output = [{ Name: "Color", Data: [] },{ Name: "Size", Data: [] }] ;
originalList.map(function(entry){
if ( entry.optionName === "Color") output[0].Data.push({ Id: entry.Id, Name: entry.Name });
if ( entry.optionName === "Size") output[1].Data.push({ Id: entry.Id, Name: entry.Name });
});
'use strict'
let l = [ { Id: 1, Name: 'Red', optionName: 'Color' },
{ Id: 2, Name: 'Yellow', optionName: 'Color' },
{ Id: 3, Name: 'Blue', optionName: 'Color' },
{ Id: 4, Name: 'Green', optionName: 'Color' },
{ Id: 7, Name: 'Black', optionName: 'Color' },
{ Id: 8, Name: 'S', optionName: 'Size' },
{ Id: 11, Name: 'M', optionName: 'Size' },
{ Id: 12, Name: 'L', optionName: 'Size' },
{ Id: 13, Name: 'XL', optionName: 'Size' },
{ Id: 14, Name: 'XXL', optionName: 'Size' } ];
let color = [];
let size = [];
l.forEach(element => {
if (element['optionName'] === 'Color') {
color.push({'Id': element.Id, 'Name': element.Name});
} else {
size.push({'Id': element.Id, 'Name': element.Name});
}
});
console.log(color);
console.log(size);
You can try this method.
All of the answers lead to the same result, so it all comes down to a personal preference (or company guidelines) on how to tackle this.
// ES5 (traditional javascript) version
function groupByOptionName(list, optionName) {
return list
// filter out any item whose optionName does not match the desired name
.filter(function(item) {
return item.optionName === optionName;
})
// map the item into the desired shape
// (appears to be everything except optionName itself
.map(function(item) {
return {
Id: item.Id,
Name: item.Name
};
})
}
// ES2015/ES6 version
function groupByOptionName(list, optionName) {
return list
// filter out any item whose optionName does not match the desired name
.filter(item => item.optionName === optionName)
// map the item into the desired shape
// (appears to be everything except optionName itself
.map(item => {
Id: item.Id,
Name: item.Name
});
}
This function would let you program the desired result as follows:
var output = [
{Name: 'Color', Data: groupByOptionName(list, 'Color')},
{Name: 'Size', Data: groupByOptionName(list, 'Size')},
];
// the ES2015/ES6 version of this code would replace var with let
While the code itself differs, it is much like the other answers, with only a variation on the steps needed.
One could also opt to leave out any hardcoded option names (Color and Size) by extracting those aswel, this would allow for a more dynamic input, but could also introduce more processing that actually needed.
// ES5 (traditional javascript) version
function getOptionNames(list) {
return list
// map the array into a list of optionNames
.map(function(item) {
return item.optionName;
})
// remove duplicates
.filter(function(item, index, all) {
return all.indexOf(item) === index;
});
}
// ES2015/ES6 version (does exactly the same as the one above)
function getOptionNames(list) {
return list
// map the array into a list of optionNames
.map(item => item.optionName)
// remove duplicates
.filter((item, index, all) => all.indexOf(item) === index);
}
Which allows the result to be fully based on the input data:
// ES5 (traditional javascript) version
var output = getOptionNames(list)
// map the names into the desired structure
.map(function(buffer, name) {
return {
Name: name,
Data: groupByOptionName(list, name)
};
});
// ES2015/ES6 version (does exactly the same as the one above)
var output = getOptionNames(list)
// map the names into the desired structure
.map((buffer, name) => {
Name: name,
Data: groupByOptionName(list, name)
});
By writing all of the data-mangling steps in short consice steps you'd do yourself (especially your future self) a favor if this code ever needs to be adjusted.
If the data set really is heavy (in terms of a lot of data), you must also make sure to keep the number of copies you keep in memory limited. For example, if you never need the original dataset, make sure it can be garbage collected (by not having a variable containing it outside the scope where you receive the data)
Usage:
groupValues([
{ color: 'blue', value: 100 },
{ color: 'blue', value: 75 },
{ color: 'yellow', value: 50 },
{ color: 'yellow', value: 25 }
], 'color')
Result:
[
[{ color: 'blue', value: 100 }, { color: 'blue', value: 75 }],
[{ color: 'yellow', value: 50 }, { color: 'yellow', value: 25 }]
]
Function:
const groupValues = function(arr, key) {
const mapped = {}
arr.forEach(el => {
const actualKey = el[key]
if(!mapped.hasOwnProperty(actualKey)) mapped[actualKey] = []
mapped[actualKey].push(el)
})
return Object.keys(mapped).map(el => mapped[el])
}
I'd like to have a dojo grid which connects to a server url which outputs the following json :
{identifier : "id"
items : [ { id: "1", name: "John", university : { name: "XXX", address: "YYY" } }].
Basically I have a nested json. I would like to represent the university name and University address as separate columns in the grid.
I tried using the dojox.grid.DataGrid object and creating a gird layout, but do not know how to refer to the nested elments and university.name and university.address don't seem to work.
I am using dojo 1.6.1.
Does anybody have any pointers?
This is the js code I use :
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.addOnLoad(function(){
// our test data store for this example:
var jsonStore = new dojo.data.ItemFileReadStore({
url: '/MainDeployer/ajax/users/get.json'
});
var layoutUsers = [
[{
field: "name",
name: "Name",
width: 10
},
{
field: "university.name",
name: "University Name",
width: 10
},
{
field: "university.address",
name: "University Address",
width: 'auto'
}]];
// create a new grid:
var grid = new dojox.grid.DataGrid({
query: {},
store: jsonStore,
clientSort: true,
rowSelector: '20px',
structure: layoutUsers
},
document.createElement('div'));
dojo.byId("usersTable").appendChild(grid.domNode);
grid.startup();
});
Thanks,
Cristian
What kind of store are you using? Have a look at the dojo.data.ItemFileReadStore documentation, there is an example with a situation like yours:
http://dojotoolkit.org/reference-guide/dojo/data/ItemFileReadStore.html#item-structure
This would help you fetching all the items with a single call to the method "fetch". If for some reasons it doesn't work due to the different json structure, you can continue using ItemFileReadStore , and create a function that loops over all the objects in your json and uses the loadItem method for adding items one by one in this way (it's not beautiful but it works):
var myData = {"items" : []};
var myStore = new dojo.data.ItemFileWriteStore({data: myData});
var myLayout = [{
field: 'name',
name: 'Name',
width: '200px'
},
{
field: 'universityName',
name: 'University Name',
width: '100px'
},
{
field: 'universityAddress',
name: 'University Address',
width: '60px'
}];
var myGrid;
dojo.addOnLoad(function(){
myGrid = new dojox.grid.DataGrid({
store: myStore,
structure: myLayout
}, document.createElement('div'));
dojo.byId("myGridContainer").appendChild(myGrid.domNode);
myGrid.startup();
dojo.xhrGet({
url: myURL,
handleAs: "json",
headers: {
"Content-Type": "application/json; charset=uft-8",
"Accept" : "application/json"
},
load: function(responseObject, ioArgs) {
myList = responseObject;
dojo.forEach(myList.items, function(element) {
myStore.newItem({"name": element.name,
"universityName": element.university.name,
"universityAddress": element.university.address});
});
})
});
}
se a formatter:
var nameFormatter = function(value, rowIdx){
return value.name;
};
var addressFormatter = function(value, rowIdx){
return value.address;
};
var layoutUsers = [
[{
field: "name",
name: "Name",
width: 10
},
{
field: "university",
name: "University Name",
width: 10,
formatter: nameFormatter
},
{
field: "university",
name: "University Address",
width: 'auto',
formatter: addressFormatter
}]];
I need to set up a CheckboxGroup checkboxes with values loaded with json from some url.
What is a correct format of JSON?
Many thanks for help!
Update: I'll clarify my problem.
I'm using EditorGridPanel. Rows are Periods. There are columns Start_at, Finish_at, Region. First and second are date and everything ok with them. Problem with Region which actually is a CheckboxGroup with a checkbox for each week day - Monday, Tuesday, etc. So:
First I'm loading data from server into store
function setupDataSource() {
row = Ext.data.Record.create([
{ name: 'start_at', type: 'string' },
{ name: 'finish_at', type: 'string' },
{ name: 'region', type: 'string' }
]);
store = new Ext.data.Store({
url: '/country/195/periods',
reader: new Ext.data.JsonReader(
{
root: 'rows',
id: 'id'
},
row
)
});
store.load();
}
URL url: '/country/195/periods' returns JSON:
{"rows": [{"region": {"cbvert_1": 1, "cbvert_2": 0, "cbvert_3": 1, "cbvert_4": 0, "cbvert_5": 1, "cbvert_6": 0, "cbvert_7": 1}, "start_at": "2010-10-17", "id": 1, "finish_at": "2010-10-28"}]}
Then I'm building a grid:
function buildGrid() {
sm = new Ext.grid.RowSelectionModel();
cm = new Ext.grid.ColumnModel([
// ... Start at and Finish at columns definition here ...
{ header: 'Region',
dataIndex: 'region',
width: 150,
editor: new Ext.form.CheckboxGroup({
xtype: 'checkboxgroup',
columns: 7,
vertical: true,
items: [
{boxLabel: 'M', name: 'cbvert_1', inputValue: 1},
{boxLabel: 'T', name: 'cbvert_2', inputValue: 1},
{boxLabel: 'W', name: 'cbvert_3', inputValue: 1},
{boxLabel: 'T', name: 'cbvert_4', inputValue: 1},
{boxLabel: 'F', name: 'cbvert_5', inputValue: 1},
{boxLabel: 'S', name: 'cbvert_6', inputValue: 1},
{boxLabel: 'S', name: 'cbvert_7', inputValue: 1},
]
}),
renderer: function(value) {}
}]);
// ...
}
So, when I'm clicking on a grid cell I need to get checkboxes preselected with values previously stored in database. Now all checkboxes are stay blank but should be 1010101 as its in JSON.
Please point me to errors or maybe a some kind of a solution. Any help will be greatly appreciated.
Many thanks!
Check this out:
http://www.sencha.com/forum/showthread.php?47243-Load-data-in-checkboxgroup
Updated:
Remove the type declaration of the region field. You do not need a string but an object (from JSON). It works just fine that way :)