Checking to see if key-value has the same value - javascript

So I'm turning a .csv file into an array of key-value pairs, I'm trying to print each unique value and i'm trying to figure out how I can check to make sure the values aren't identical. So for example:
var data = $.csv.toObjects(csv);
will turn everything into
[
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"}
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
I want to check if heading1 has the same value in both instances and if it does to only print the first instance of that value.

Convert your data into key–value pairs, where keys are the values from "heading1" like so:
var data = [
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"},
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" },
];
var filtered = {};
for (var i = 0, max = data.length; i < max; i++) {
var record = data[i];
if (!filtered[record.heading1]) {
filtered[record.heading1] = {};
}
filtered[record.heading1] = record;
}
var keys = Object.keys(filtered);
for (var i = 0, max = keys.length; i < max; i++) {
console.log(filtered[keys[i]]); // do print
}

Related

How to parse a string into no type

I am parsing a csv file:
let lines = csvData.split(/\r\n|\n/);
let headers = lines[0].split(',');
for (let i = 1; i < lines.length; i++) {
let values = lines[i].split(',');
let item = {};
for (let j = 0; j < headers.length; j++) {
item[headers[j]] = values[j];
}
items.push(item);
}
return items;
I am getting its data. However, the data are all strings. I want to pass them into JSON, and make them have no type, so I can pass them into variables with different types. I don't want to use parseInt/parseFloat directly, because I don't know the specific type of each variable.
However, each time I pass the values to JSON, they are all strings, e.x. "1234", not 1234. Normally I can pass JSON data to class without no type, but this time I convert the csvData into JSON, the JSON data are all strings. I guess it is because the split function makes it a string?
Optional:
I can pass the type into this function, like readCsvFile<T>(csvData), can I do something like:
if (typeof(T[headers[j]]) == 'number') {
item[headers[j]] = parseFloat(values[j]);
} else {
item[headers[j]] = values[j];
}
But T[header[j]] doesn't pass the compilation.
I would do something more functional.
//Define variables
var csvData = "field1a,field2a,field3a\r\nfield1b,field2b,field3b";
var linesAsObjects = [];
var lines = csvData.split(/\r\n|\n/);
//Split fields here
var splitFields = function(line){
let fields = line.split(',');
addItem(fields);
}
// Assign field values to object or formatting here
var addItem = function(fields){
let obj = {};
obj.field1 = fields[0];
obj.field2 = fields[1];
obj.field3 = fields[2];
linesAsObjects.push(obj);
}
// Call the code for each line
lines.forEach(splitFields);
//Printing lines and fields as assigned to an object.
console.log(linesAsObjects);
If you don't need to know the type (and you actually not trying to get the value of the property with the unknown type), then you can use the "unknown" type https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html
This is far better than "any" and you can type the data at the point you need to get it.
Try to use type any for the attributes.
// add the fields you have from the CSV
class ResultFromCSV {
myValue: any;
otherValue: any;
}
...
let lines = csvData.split(/\r\n|\n/);
let headers = lines[0].split(',');
for (let i = 1; i < lines.length; i++) {
let values = lines[i].split(',');
// instantiate here
let item = new ResultFromCSV();
for (let j = 0; j < headers.length; j++) {
item[headers[j]] = values[j];
}
items.push(item);
}
return items;

Looping through Json and appending to object

I have this JSON response from Google Maps, saved to a .json file. It's a search for schools nearby.
I only want to extract the name and the location of the schools, and save these to the elemSchoolsArr variable for use later.
I don't know why the code I have below doesn't loop through the json response, checking elemSchoolsObj only show one object, instead of 10, which I would want to push to the elemSchoolsArr later.
var elemSchoolsArr = [];
var elemSchoolsObj = {};
$.getJSON('elementary-schools.json', function(data){
for (var i = 0; i < 10; i++) {
elemSchoolsObj.title = data.results[i].name;
elemSchoolsObj.location = data.results[i].geometry.location;
}
});
elemSchoolsArr.push(elemSchoolsObj);
You just need to push the object in to the array inside of the loop, so that each object is pushed in, rather than just one. Obviously this code snippet won't actually run because we're not getting your JSON here.
var elemSchoolsArr = [];
$.getJSON('elementary-schools.json', function(data){
for (var i = 0; i < 10; i++) {
var elemSchoolsObj = {};
elemSchoolsObj.title = data.results[i].name;
elemSchoolsObj.location = data.results[i].geometry.location;
elemSchoolsArr.push(elemSchoolsObj);
}
});
Here's a functional example...
var array = ["a", "b", "c", "d", "e"];
var first_try = [];
var second_try = [];
for( var i = 0; i < array.length; i++ ){
// we define our object in the loop but don't add it to the array
var obj = {
item: array[i]
};
}
// we push one object in to the array
first_try.push( obj );
// we get one object in the array
console.log( first_try );
for( var i = 0; i < array.length; i++ ){
// we define our object in the loop
var obj = {
item: array[i]
};
// we push each object we define in the loop in to the array
second_try.push( obj );
}
// we get all the objects in the array
console.log( second_try );

Dynamic Key Value Array with Multiple Values in Javascript

I have:
var data = [];
I want to dynamically create string array like this:
for(var i=0; i < files.length; i++){
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
Is this possible? I tried it and it complained 'Cannot set property 'part1' of undefined'
Then I want to sort the data array by part1 values so:
data[0] = {3,a,b};
data[1] = {1,a,b};
data[2] = {5,a,b};
becomes:
data[0] = {1,a,b,c};
data[1] = {3,a,b,c};
data[2] = {5,a,b,c};
The reason I want to do this is because after the sort is done, i need to change the
data[i].part2
to something else after sorting!
You could do this:
for (var i = 0; i < files.length; i++) {
data[i] = {};
data[i].part1 = "abc";
data[i].part2 = "def";
data[i].part3 = "ghi";
}
to set data[i] to an empty object, then fill it piece by piece. Or
for (var i = 0; i < files.length; i++) {
data[i] = {
part1: "abc",
part2: "def",
part3: "ghi"
};
}
to set data[i] to the complete object all at once.
I don't understand the data[0] = {3,a,b}; part, though: {3,a,b} is a syntax error and it doesn't resemble your other code (which doesn't mention 3 or a or b).
But you can easily sort an array of objects by a particular property:
data.sort(function (a, b) {
return (a.part1 > b.part1) - (a.part1 < b.part1);
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for details.

JavaScript for loop closure issue

I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.

making an array from other array items

I have the following problem:
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
i need to group them so that the end output is on array in the following format:
var store = [ ['4','kiwi','yes'],['5','orange','no'], ...]
im so confused as in how to make one array with these values into a 2d array. thanks
Using JavaScript with some overkill :):
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
// if the lengths/size of the above arrays are the same
var store = [];
for(var i = 0, len = price.length; i < len; i++) {
store.push([price[i], produce[i], stock[i]]);
}
// if the lengths/size of the above arrays aren't the same and you want the minimum full entries
var storeMin = [];
for(var i = 0, len = Math.min(price.length, produce.length, stock.length); i < len; i++) {
storeMin.push([price[i], produce[i], stock[i]]);
}
// if the lenghts/size of the above arrays aren't the same and you want the maximum entries with defaulting missing values to null
// replace the nulls by any default value want for that column
var storeMax = [];
for(var i = 0, pLen = price.length, prLen = produce.length, sLen = stock.length, len = Math.max(pLen, prLen, sLen); i < len; i++) {
storeMax.push([pLen>i?price[i]:null, prLen>i?produce[i]:null, sLen>i?stock[i]:null]);
}
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
var store = [];
$.each(price,function(ind,elm) {
store.push([elm,produce[ind],stock[ind]]);
});
console.log(store);

Categories

Resources