I have used csvtojson in order to write the csv data into a sql database, the object that the funcion return to have this structure:
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
How can I acces to each field? I am trying to do console.log(prueba[0]["Capacidad"]) in order to see if it is running but it prints "undefined".
'Aula;Capacidad' is seen as a key, so you only can do the following:
console.log(prueba[0]["Aula;Capacidad])
which will write
A10+11;112
to the console.
Your properties are actually named 'Aula;Capacidad', meaning you'd need to use prueba[0]['Aula;Capacidad'] to get the value you are looking for.
This is what you need to iterate through the list of items:
var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }];
for (var i = 0; i < prueba.length; i++) {
console.log(prueba[i]);
}
If you need to go deeper and iterate over every item properties:
var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }];
for(var i = 0; i < prueba.length; i++) {
for(var p in prueba[0]) {
console.log(p, prueba[i][p]);
}
}
Your key you are looking up is in a composite key. So you would need to look it up with that composite key and than split it.
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
console.log(prueba[0]['Aula;Capacidad'].split(";")[1]);
Other choice is to parse it all and look it up by the key.
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
const parsed = prueba.reduce(function (arr, row) {
const entry = Object.entries(row)[0];
const keys = entry[0].split(";");
const values = entry[1].split(";");
const data = keys.reduce(function (o, key, index) {
o[key] = values[index];
return o;
}, {});
arr.push(data);
return arr;
}, []);
console.log(parsed[0].Capacidad);
console.log(parsed[1].Capacidad);
Your data looks malformed so you might need to do some manual processing.
You have an array of two items, both with a single key-value in them. You can do console.log(prueba[0]["Aula;Capacidad"]) and this will return 'A10+11;112'.
You might need to split things by the ; there so you could do something like this:
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
prueba.forEach(item => {
const splitItem = item["Aula;Capacidad"].split(";");
console.log("Each item now looks like this: " + splitItem)
// You can access the first and second part of the item like this
console.log(splitItem[0], splitItem[1])
})
To be honest, I'd go back and look at how this data is being added to your DB. It looks messed up.
Related
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']))
I was wondering how i could merge these two objects retrieve the tag values and store them in an array. This data is also coming from a json response so incoming data should be pushed onto the end of the new array.
so it would look something like this
["2011 LDI", "2012 LDI"]
array with incoming data:
["2011 LDI", "2012 LDI","2013 LDI"]
Here is what I am getting back in my console.log:
[19-08-25 21:58:32:055 PDT] []
[19-08-25 21:58:32:056 PDT] []
Here are the two objects of arrays i am trying to merge:
{date_added=2019-08-26 04:19:00.112083, tag=LDI 2011}
{date_added=2019-08-26 04:19:00.112089, tag=LDI 2012}
and I want it to look like this
[LDI 2011, LDI 2012]
and how I am trying to do it.
var tagtest = [];
var tags = message.student_detail.student_tags,
i = 0,
len = tags.length;
for (i; i < len; i++) {
var obj = tags[i];
for (a in obj) {
}
Array.prototype.push(tags, tagtest);
Logger.log(tagtest)
}
Based on your desired output ([LDI 2011, LDI 2012]), You may want the only tag values from the array, If this is what you are looking for then .map() will help you
const array = [
{
date_added: '2019-08-26',
tag: 'LDI 2011'
},
{
date_added: '2019-08-26',
tag: 'LDI 2012'
}];
const tags = array.map((r) => {
const chunk = r.tag.split(' ');
return `${chunk[1]} ${chunk[0]}`;
} );
console.log(tags);
A for in loop is a great way to work with objects. I updated the code above so that it was actually an array of objects, not an error. See below :)
var data = [{date_added: "2019-08-26 04:19:00.112083", tag: "LDI 2011"},
{date_added: "2019-08-26 04:19:00.112089", tag: "LDI 2012"}];
var newArr = [];
for(var item in data) {
newArr.push(data[item].tag);
}
console.log(newArr);
I have an array of filters, where i get the name of filter, operator & value
e.g.
[{name="pricing.price", op="gte", value=10000}, {name="pricing.price", op="gte", value=10000}]
when the user refreshes after applying the filter, the last filters are saved into this.savedFilters
and after the refresh, the user can add new filters or modify the existing filters.
add new filters -> works fine
modify existing filters -> NOT working fine
I made a function, which is partially doing the job, if I am running it, it's updating the value only once, and then next time I update, it's not updating anything.
JSFiddle: https://jsfiddle.net/cdr8btwe/
//if there are no saved filters, the new filters are the final filters
if (!this.savedFilters) {
this.finalFilters = this.freshFilters;
} else {
//concat the new & saved filters & move into a temp array
this.tempArrayOfFilters =
this.freshFilters.concat(this.savedFilters);
//forEach loop to check
this.tempArrayOfFilters.forEach((value) => {
const key = value['name'] + '_ ' + value['op'];
if (this.mapping[key]) {
} else {
this.finalFilters.push(value);
this.mapping[key] = true;
}
});
}
console.log('finalFilters:', this.finalFilters);
[
{name:"pricing.price",op:"gte",value:1234}, {name:"pricing.price",op:"lte",value:1111}
]
When the person is modifying saved filters,
lets say
this.freshfilters = [{"name":"pricing.price","op":"gte","value":5678},
{"name":"pricing.price","op":"gte","value":9999}]
output is coming
[{name:"pricing.price", op:"gte", value:1234},
{name:"pricing.price", op:"lte", value:1111}]
the output should be
[{name:"pricing.price",op:"gte",value:5678},{name:"pricing.price",op:"lte",value:9999}]
because if name & op is the same, just update the value.
Try this, I'm not sure exactly what you are trying to do but hopefully this will be of some use to you.
let arr1 = [{name: "pricing.price", op:"gte", value:1234}];
let arr2 = [{name: "pricing.price", op:"gte", value:5678}];
let arr3 = [{name: "pricing.price", op:"lte", value:1111}];
let arr5 = [{name: "pricing.price", op:"lte", value:9999}];
let arr4 = []
arr4 = arr4.concat(arr1, arr2, arr3, arr5);
final_arr = []
mapping = {} // truthy mapping of name and p.p
arr4.forEach((value) => {
key = value["name"]+'_ '+value["op"]
final_arr[key] = value;
//if (mapping[ key ]) {
//} else {
//final_arr.push(value)
mapping[key] = true
//}
})
//Current Output
/*
[
{name:"pricing.price", op:"gte", value:1234},
{name:"pricing.price", op:"lte", value:1111}
]
*/
//Expected Output
/*
[
{"name":"pricing.price","op":"gte","value":5678},
{"name":"pricing.price","op":"lte","value":9999}
]
*/
console.log('final_arr: ', final_arr)
jsfiddle
I want to find strings that has data from the strings from the array 2 in the array1 and save result as separate uniq array.
As can you see I search for not exact values. From the array1 values I know only part of the information, and I want to find the complete strings, with that information, in array1. And at the end I want to save what I found. So, I don't have a problem with finding here, but a problem with saving in the valid single JSON.
Array examples:
Array #1:
{
"overflow": [
"id:address:name:location:email",
...
"id2:address2:name2:location2:email2"
]
}
Array #2:
[
"location:email",
...
"location2:email2"
]
Code:
resultArr: function() {
var arr1 = '/var/log/1.json';
var arr2 = '/var/log/2.json';
var arrResult = '/var/log/result.json';
var arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
for (var i = 0; i < arr2Obj.length; i++) {
var arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return e.includes(arr2Obj[i])
});
fs.appendFile(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
}
My result:
[{
"overflow": [
"id:address:name:location:email"
]
}{
"overflow": [
"id54:address54:name54:location54:email56"
]
}{
"overflow": [
"id2:address2:name2:location2:email2",
"id6:address6:name6:location2:email2"
]
}
What I really want:
{
"overflow": [
"id:address:name:location:email",
"id54:address54:name54:location54:email56",
"id6:address6:name6:location2:email2",
"id2:address2:name2:location2:email2"
]
}
Instead of reading the file again and again, and appending to the result repeatedly, just do both actions only once. All the rest should happen in memory.
You will also get better results (no risk for duplicates in result) when you swap the loops: put the filter action as the outer loop. For the inner loop you can use some, since one match is enough for the entry to be included:
resultArr: function() {
var arr1 = '/var/log/1.json',
arr2 = '/var/log/2.json',
arrResult = '/var/log/result.json',
arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8')),
arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return arr2Obj.some(function (f) {
return e.includes(f)
});
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
At each iteration, you're creating a new object and appening it to a file.
JSON is not a good format to append to.
You're replacing the array instead of adding fields to it.
You can do it that way, it should work :
resultArr: () => {
let arr1 = '/var/log/1.json';
let arr2 = '/var/log/2.json';
let arrResult = '/var/log/result.json';
let arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
let arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8')); // reading only one time
arr1Obj.overflow = arr2Obj.map(value => {
return arr1Obj.overflow.filter(e => return e.includes(value))
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8'); //Writing only one time
}
Array.map() executes the closure for each field in your array and group all the values returned by the closure in another array.
I also replaced some keywords to make your code more ES6 compliant. I you really want to append, you should use CSV and not JSON.
I have an array of objects that looks like this:
[
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];
Is there a way to get the list of all countries from the array above, and get rid of the repeated ones?
So from the list above, the list I am to obtain is:
["USA", "Taiwan", "Great Britain"]
Thank you!
Just loop over people and insert unique countries in a new array. Here is an example.
var countries = [];
var people = [
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];
for (var i = 0, l=people.length; i < l; i++) {
if(people[i] && people[i].from) {//ensure country exists
if (countries.indexOf(people[i].from) == -1) {//ensure unique
countries.push(people[i].from);
}
}
}
Yet another variant with reduce
var arr = [
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];
var countries = arr.reduce(function(acc, cur){
if(!acc.map[cur.from]){
acc.map[cur.from]=true;
acc.result.push(cur.from);
}
return acc;
}, {result:[], map:{}}).result;
var arr = [
{"name":"Andrea","from":"USA","Food":"Candy"},
{"name":"Matt","from":"Taiwan","Food":"Chicken"},
{"name":"Roddy","from":"USA","Food":"Rice"},
{"name":"Andy","from":"Great Britain","Food":"Steak"},
];
var countries = arr.reduce(function(acc, cur){
if(!acc.map[cur.from]){
acc.map[cur.from]=true;
acc.result.push(cur.from);
}
return acc;
}, {result:[], map:{}}).result;
document.getElementById('countries').innerHTML = countries.join();
<span id="countries"></span>
If you are already using the excellent Lodash library, the following will do it for you neatly in one line:
var uniqueCountries = _(dataArray).pluck('from').unique().value();
UnderscoreJS has similar functionality using chaining.
For D3.js, the following will do it:
var uniqueCountries = d3.set(dataArray.map(function (x) { return x.from; })).values();
Without doing the unique-ifying on the server and returning that data separately, there is no way to get around looping through all records at least once to do this. For 1000 records or so, though, this will still be very fast.
For plain JS, see other answers.
I'd loop over the Array and put the country into an array if it is not yet inside that array.