Vue.js JSON grouping array multiple times - javascript

I have an application that I use to import a CSV file which then converts it to JSON.
The JSON output looks like this
{
"Class": "Gecultiveerde paddestoelen",
"Soort": "Shii-take",
"Sortering": "Medium",
"LvH": "SP",
"Omschrijving": "SHIITAKE MEDIM STEMLESS unclosed",
"Trade unit composition": "8 x 150gr",
"Punnet type": "CARTON",
"CONTAINER BOX": "Multicrate (30x40x11)",
"Price (/box)": "10",
"Amount (container box) per Pallet / Europallet \r": "200 / 160\r"
}
Console log output
I need to groupBy on Class > Soort > Sortering which I don't know how to do in VUE/JS.
I am able to groupBy single colls like this
In the methods:
groupBy: function (array, key){
const result = {};
array.forEach(item => {
if (!result[item[key]]){
result[item[key]] = []
}
result[item[key]].push(item)
});
return result
},
Computed:
groups() {
return this.groupBy(this.parse_csv, 'Class');
},
In SQL this is very easy to do like this DBFiddle (the dbfiddle has all of the JSON data in it)
The expected output would be like
After obviously doing my fair share of googling and researching I have stumbled upon this answer.
However I am not able to get this working in VUE as this is plain JS, this most likely is a mistake on my behalf for not being very familiar with js, but I would love some extra take on this.

Instead of using a single key as parameter, you can get array of keys. Then create a unique key based on the values for each of those keys separated by a |.
groupBy: function(array, keys){
const result = {};
array.forEach(item => {
// get an array of values and join them with | separator
const key = keys.map(k => item[k]).join('|');
// use that unique key in result
if (!result[key]){
result[key] = []
}
result[key].push(item)
});
return result
}
For the object you've posted, the unique key would look like this:
Gecultiveerde paddestoelen|Shii-take|Medium
Here's a snippet:
function groupBy (array, keys){
const result = {};
array.forEach(item => {
const key = keys.map(k => item[k]).join('|');
if (!result[key]){
result[key] = []
}
result[key].push(item)
});
return result
}
const input=[{Class:"Gecultiveerde paddestoelen",Soort:"Shii-take",Sortering:"Medium",LvH:"SP",Omschrijving:"SHIITAKE MEDIM STEMLESS unclosed","Trade unit composition":"8 x 150gr","Punnet type":"CARTON","CONTAINER BOX":"Multicrate (30x40x11)","Price (/box)":"10","Amount (container box) per Pallet / Europallet \r":"200 / 160\r"}];
console.log(groupBy(input, ['Class', 'Soort', 'Sortering']))

Related

How to iterate over only specific keys from a JSON array object using javascript

I am having a below json array and now I need to iterate over the json object to retrieve two values of fields ServicePort And ServiceAddress and form a final output as {"MyIp" : "http://IP:Port"} from my json array object.
var bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
I have tried as below to iterate
for (var key in bodyObject ) {
if (bodyObject.hasOwnProperty(key)) {
console.log(bodyObject[key].ServiceAddress);
console.log(bodyObject[key].ServicePort);
}
}
How can I form a output final output like {"MyIp" : "http://IP:Port"} from my json array object each hitting giving me a diffrent Ip's from my above JSON list dynamically. Can someone help on this please
I think you're asking how to create a new array with a single object with a MyIp property whose value is the combination of ServiceAddress and ServicePort. map is the idiomatic way to do that, perhaps with some destructuring to pick out the properties from each object and a template literal to build the resulting string:
const result = bodyObject.map(({ServiceAddress, ServicePort}) => {
return {MyIp: `http://${ServiceAddress}:${ServicePort}`};
});
or with a concise-form arrow function:
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
(You need the () around the object literal because otherwise it looks like the full function body form of arrow function to the parser.)
Live Example:
const bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
console.log(result);
That has a fair number of newish JavaScript features in it, so just for clarity here's a version without destructuring or a template literal:
const result = bodyObject.map(element => {
return {MyIp: "http://" + element.ServiceAddress + ":" + element.ServicePort};
});

Javascript String splitting and Organizing based on first letter

I am currently working a project that I have to use js and php to retrieve data from the gateway. Now that i have retrieved it, but the data is not organised:
{"timestamp":1526524809413,"data":[
{"_id":"rJeixnNtpG","data":"N11B00074","raw":
[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},
{"_id":"HkzognEYpf","data":"N11E00000","raw":
[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},
{"_id":"BJxXp4t6M","data":"N11A00029","raw":
[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}
As you can see there are three types of data: the one starts with B(N11B00074), E(N11E00000) and A(N11A00029), followed by the 5 digits which is the data i wanted to split from the string while categorised by the type(B, E and A).
I have three tables in my web page and want to put the data into them based on the types: Like B being humidity table, A being temperature table and E being pH readings table.
So far i only managed to list them out in a table.
Is there a way that I can seperate the string and put them into an array based on their types?
You can use reduce to group objects in an array:
const input={"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw":[78,49,49,66,48,48,48,55,52],"timestamp":1525398515116},{"_id":"HkzognEYpf","data":"N11E00000","raw":[78,49,49,69,48,48,48,48,48],"timestamp":1525398515479},{"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]}
const arranged = input.data.reduce((accum, obj) => {
const { data } = obj;
const type = data[3];
const digits = data.slice(5);
if (!accum[type]) accum[type] = [];
accum[type].push({ ...obj, digits });
return accum;
}, {});
console.log(arranged);
// If you want an array and not an object:
console.log(Object.values(arranged));
If you want to group the array into an object. You can use reduce. You can get the fourth character of the string by using charAt
let arr = {"timestamp":1526524809413,"data":[{"_id":"rJeixnNtpG","data":"N11B00074","raw": [78,49,49,66,48,48,48,55,52],"timestamp":1525398515116}, {"_id":"HkzognEYpf","data":"N11E00000","raw": [78,49,49,69,48,48,48,48,48],"timestamp":1525398515479}, {"_id":"BJxXp4t6M","data":"N11A00029","raw":[78,49,49,65,48,48,48,50,57],"timestamp":1525398807747}]};
let result = arr.data.reduce((c, v) => {
let l = v.data.charAt(3); //Get the 4th chatacter
c[l] = c[l] || [];
c[l].push(v);
return c;
}, {});
console.log( result );

javascript sort key value pair on frequency in different array

I would like to store product information in a key, value array, with the key being the unique product url. Then I would also like to store the visit frequency of each of these products. I will store these objects as window.localStorage items, but that's not very important.
The thing I had in mind was two key value arrays:
//product information
prods["url"] = ["name:product_x,type:category_x,price:50"]
//product visits frequency
freq["url"] = [6]
Then I would like to sort these prods based on the frequency.
Is that possible?
Hope you guys can help! Thanks a lot
Well you seem to have made several strange choices for your data format/structure. But assuming the format of the "prod" is beyond your control but you can choose your data structure, here's one way to do it.
Rather than two objects both using url as a key and having one value field each I've made a single object still keyed on url but with the product and frequency information from each in a field.
Objects don't have any inherent order so rather than sorting the table object I sort the keys, your "url"s ordered by ascending frequency.
To show that it's sorted that way I print it out (not in the same format).
For descending frequency, change data[a].freq - data[b].freq to data[b].freq - data[a].freq
var data = {
"url": {
prod: "name:product_x,type:category_x,price:50",
freq: 6
},
"url2": {
prod: "name:product_y,type:category_y,price:25",
freq: 3
}
};
var sorted = Object.keys(data).sort((a, b) => data[a].freq - data[b].freq);
console.log(sorted.map(k => [data[k].freq, k, data[k].prod]));
There's more than one way to format the data, which would change the shape of the code here.
maybe something like this:
var prods = [
{url:1, val:[{name:'a',type:'x',price:60}]},
{url:2, val:[{name:'b',type:'x',price:30}]},
{url:3, val:[{name:'c',type:'x',price:50}]},
{url:4, val:[{name:'c',type:'x',price:20}]},
{url:5, val:[{name:'c',type:'x',price:10}]},
{url:6, val:[{name:'c',type:'x',price:40}]}
];
var freq = [
{url:1, freq:6},
{url:2, freq:3},
{url:3, freq:5},
{url:4, freq:2},
{url:5, freq:1},
{url:6, freq:4}
];
prods.sort(function (a, b) {
var aU = freq.filter(function(obj) {
return obj.url === a.url;
});
var bU = freq.filter(function(obj) {
return obj.url === b.url;
});
if (aU[0].freq > bU[0].freq) {
return 1;
}
if (aU[0].freq < bU[0].freq) {
return -1;
}
return 0;
});

getting distinct values from array of arrays in Javascript

My data is in the following format..
var data= [['typeName', 'valueName'], ['type1', 'value1'],
['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
I wish to transform the above data to data as below..
var resultdata=[{'typeName':'type1','valueName':['value1','value2']},
{'typeName':'type2','valueName':['value3','value4']}]
Basically I pick up distinct 'typeName' values and then group 'valueName' values by 'typeName' values.
I would preferably use only knockoutjs, lodash or underscorejs as my soln already uses them but I'm open to other solutions as well..
All help is sincerely appreciated
Thanks
I think this solution using underscore should do the trick:
var result= _.chain(data)
.rest()
.groupBy( value => value[0])
.map( (value,key) => ({ [data[0][0]]: key, [data[0][1]]: _.map(value, val => val[1])}))
.value();
This solution uses rest to skip the first item in the data array (the type descriptors). The array is then grouped by the first value in the array (the type) and the mapping returns the grouping in the required form using es6 object initializer notation.
Given the result as:
var resultdata=[
{'typeName':'type1'},{'valueName':['value1','value2']},
{'typeName':'type2'},{'valueName':['value3','value4']}
]
I'm going to call 'typeName' the category and 'valueName' the items.
Since the original data look like this:
var data= [
['typeName', 'valueName'],
['type1', 'value1'],
['type1', 'value2'],
['type2', 'value3'],
['type2', 'value4']
]
It is clear there is a pattern. The first row of data is what we'll use as labels for category and items. All the remaining data represent the values being used inside category and items.
The first step is to extract the labels:
var categoryLabel = data[0][0];
var itemLabel = data[0][1];
Next, the unique categories will need to be determined, so we'll use reduce to build an array of unique categories:
var categories = data
.filter(function(row, i) { return i > 0 }) // remove the labels
.reduce(function(arrCategories, currRow) {
// Add the current rows' category if it doesn't already exist
var currCategory = currRow[0];
if (arrCategories.indexOf(currCategory) === -1) {
return arrCategories.concat(currCategory);
}
return arrCategories;
}, [])
Now that you have a set of categories, you just need to iterate over each one to find all items that belong to it:
var valuesByCategory = {};
categories.forEach(function(category) {
// find all the data items that match the category
var items = data
.filter(function(row) { return row[0] === category; })
.reduce(function(arrItems, currRow) {
var currItem = currRow[1];
if (arrItems.indexOf(currItem) === -1) {
return arrItems.concat(currItem);
}
return arrItems;
}, []);
valuesByCategory[category] = items;
});
Now that all the data has been parsed out, the only thing left to do is build the resultant array:
var resultdata = [];
// iterate through each of the categories
categories.forEach(function(category) {
// using the category label, output an object with the label and category
var categoryObj = {};
categoryObj[categoryLabel] = category;
resultdata.push(categoryObj);
// Next, create a items object containing all the values
var itemsObj = {};
itemsObj[itemLabel] = valuesByCategory[category];
resultdata.push(itemsObj);
}
and that's it :)
The best part is that you don't need any external libraries. This is all ES2015 javascript!
Here is a lodash version of Gruff Bunnies solution:
var data= [['typeName', 'valueName'], ['type1', 'value1'], ['type1', 'value2'],['type2', 'value3'],['type2', 'value4']]
var names = data[0]
var values = _.tail(data)
console.log(JSON.stringify(
_(values)
.groupBy(0)
.map( (value, key) => ({ [names[0]]: key, [names[1]]: _.map(value, 1)}) )
.value()
))
https://jsfiddle.net/nmf1fdf5/

Searching through an array and returning a value

I need your help,
Id' like to be able to come up with a javascript function that is similar to the following code structure below, except for the fact that I am not that strong enough in programming to come up with a workable solution to work from.
I'd like to be able to input a given value, then, using that value, search through an array and return the value short name (the value on the right side of the : colon character)
function test() {
var filenames = [
"REQUEST FOR INFO":"REQI",
"MEDIA CALL":"MC",
"ISSUES NOTE":"ISN"
]
EX1.)
var value_to_search_for = "REQUEST FOR INFO (ALPHA)"
if (value_to_search_for matches the value in the array filenames) then {
return "REQI"
}
EX.2)
var value_to_search_for = "MEDIA CALL"
if (value_to_search_for matches value in the array filenames) then {
return "MC"
}
}
You can change that to object and then you can do this
var filenames = {
"REQUEST FOR INFO": "REQI",
"MEDIA CALL": "MC",
"ISSUES NOTE": "ISN"
};
var getValue = function(val, obj) {
if (val in obj) return obj[val];
}
console.log(getValue('ISSUES NOTE', filenames));
You can also change that to array of objects and then you can do this
var filenames = [
{"REQUEST FOR INFO": "REQI"},
{"MEDIA CALL": "MC"},
{"ISSUES NOTE": "ISN"}
];
var getValue = function(val, array) {
array.forEach(function(el) {
for (prop in el) {
if (prop == val) console.log(el[prop]);
}
});
}
getValue('MEDIA CALL', filenames);

Categories