i have json objects like
{"COLORS":[[1,red],[2,yellow],[3,orange]]}
{"FRUITS":[[1,apple,1],[2,banana,2],[3,orange,3], [4,grenade,1], [5,apple,2]]}
i need to make them like:
{"FRUITS":[[1,apple,red],[2,banana,yellow],[3,orange,orange], [4,grenade,red], [5,apple,yellow]]}
I think a simple nested loop is the simplest way to solve this.
As far as i know there is no "json join" feature in javascript.
Try this:
var colors = {"COLORS":[[1,"red"],[2,"yellow"],[3,"orange"]]};
var fruits = {"FRUITS":[[1,"apple",1],[2,"banana",2],[3,"orange",3], [4,"grenade",1], [5,"apple",2]]};
console.log(fruits);
for (var i = 0; i < fruits.FRUITS.length; i++) {
var temp = fruits.FRUITS[i];
for (var j = 0; j < colors.COLORS.length; j++) {
if (colors.COLORS[j][0] === temp[2]) {
temp[2] = colors.COLORS[j][1];
break;
}
};
fruits.FRUITS[i] = temp;
};
console.log(fruits);
You could even use jQuery.each() to help you iterating over array. And also use Array.prototype.filter() to find a color related to id in fruits array.
var colors = {"COLORS":[[1,"red"],[2,"yellow"],[3,"orange"]]};
var fruits = {"FRUITS":[[1,"apple",1],[2,"banana",2],[3,"orange",3], [4,"grenade",1], [5,"apple",2]]}
var f = fruits.FRUITS;
$.each(f, function(i, fruitItem) {
var colorItem = colors.COLORS.filter(function(color) {
return color[0] == fruitItem[2]
});
fruitItem[2] = colorItem[0][1]
});
console.log(fruits)
Another similar method to finnmich, using filter() instead of a nested loop.
This builds a new array and ignores entries which do not have matching ids, like a sql join:
var c = {"COLORS":[[1,"red"],[2,"yellow"],[3,"orange"]]};
var f = {"FRUITS":[[1,"apple",1],[2,"banana",2],[3,"orange",3], [4,"grenade",1], [5,"apple",2]]};
var result = [];
for(var i = 0; i < f.FRUITS.length; i++)
{
var entry = f.FRUITS[i];
var id = entry[2];
var color = c.COLORS.filter(function(v) {
return v[0] == id;
});
if(color.length > 0) {
result.push([entry[0], entry[1], color[0][1]]);
}
}
console.dir(result);
Here is a simple solution using jq. It assumes that $colors and $fruits contain the JSON values for 'colors' and 'fruits' respectively:
$colors.COLORS | map( {(.[0]|tostring): .[1] } ) | add as $dict
| $fruits
| .FRUITS |= map( (.[2]) |= $dict[tostring] )
The example below shows how to set $coloars and $fruits.
If your jq has INDEX/1, the first line above could be shortened to:
$colors.COLORS | INDEX(.[0]) | map_values(.[1]) as $dict
Explanation
The first line produces a dictionary ($dict), which is then used to make the translation.
Example
Assuming colors.json and fruits.json hold valid JSON values corresponding to the example give in the question, and that program.jq holds the above jq program, the invocation:
jq -n --argfile colors colors.json --argfile fruits fruits.json -f program.jq
yields:
{"FRUITS":[[1,"apple","red"],[2,"banana","yellow"],[3,"orange","orange"],[4,"grenade","red"],[5,"apple","yellow"]]}
Related
I'm wanting to remove duplicate values from the array tabData produced by the script below.
I've found numerous posts here that mention "removing duplicates from array", but don't seem to be relevant to my exact goal.
I've tried filter, I've tried using this answer and adjusting the variables to fit my script, but it did not remove the duplicates.
Surely there is a simple function that does exactly what I'm looking for, I'm just not finding it.
function getTabArray() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var version = ss.getRangeByName("version").getValue().toString();
var updateTabsName = "updateTabs";
var updateTabsSheet = ss.getSheetByName(updateTabsName);
var tabDataRows = updateTabsSheet.getLastRow();
var tabDataCols = updateTabsSheet.getMaxColumns() - 1;
var tabDataRange = updateTabsSheet.getRange(1, 2, tabDataRows, tabDataCols);
var tabData = tabDataRange.getValues(); // <-- REMOVE DUPLICATES
for (var i = 0; i < tabData.length; i++) {
if (tabData[0][i] != "" && tabData[0][i] > version) {
for (var j = 0; j < tabData.length; j++) {
if (tabData[j][i] != "" && j > 0) {
Logger.log("tabData[j][i] = " + tabData[j][i]); // tabData[j][i] = all values in column
}
}
}
}
}
This is the array it currently produces:
2.20200514.2,2.20200514.0,2.20200513.2,2.20200513.1,2.20200513.0,2.20200512.0,1.20200405.1,,tabDefinitions,Sheet6,Sheet6,changeLog,Sheet6,Index,,,,Sheet7,,Sheet7,settings,,,,Sheet8,,Sheet8,tabDefinitions,,,,,,,changeLog,,,,,,,updateTabs
I want to remove all duplicates (Sheet6, Sheet7, Sheet8, etc.) from the array.
EDIT:
After one more search, I found this answer which contains exactly what was answered below, but when I use any method in that answer, I still get all duplicates. Not sure what I'm doing wrong or not doing right.
var unique = tabData.filter((v, i, a) => a.indexOf(v) === i);
EDIT 2:
I realized my array was not actually "flat", so I added var tabData = tabDataRange.getValues().flat(); and now everything works!
You can use ES6 Set() function to remove the duplicates
const newArray = [...new Set(arrayWithDuplicates)];
What is the best way to consolidate this code? As it is, it works perfectly, but it needs to go up to maybe 40-50 items long, so it needs to be shortened dramatically, (I assume, with a for loop).
I'm pretty much a novice when it comes to Javascript, and trying to add arrays to an array with a loop is confusing me immensely.
The "vac1.", "vac2." ...etc, variables are used later on in the code to add pointers onto a Google Maps map.
var x = count.count; // x = a value that changes (between 1 & 50)
if(x == 1){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location]
];
}
if(x == 2){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location]
];
}
if(x == 3){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location],
[vac3.vacancy_title, vac3.vacancy_latlng, vac3.vacancy_url, vac3.vacancy_location]
];
}
...etc etc...
I have tried using a for loop, but it doesn't work and I have no idea if I am anywhere close to figuring out how to do it correctly.
var x = count.count;
locations = [];
array = [];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
Any help or advice would be greatly appreciated!
Thank you.
You need to consider them as a string:
var x = 5;
locations = [];
array = [];
for (i = 1; i <= x; i++) {
array = ['vac'+i+'.vacancy_title', 'vac'+i+'.vacancy_latlng', 'vac'+i+'.vacancy_url', 'vac'+i+'.vacancy_location'];
locations.push(array);
}
console.log(locations);
Create an array vac and use your previous code :
var x = count.count;
locations = [],
array = [],
vac = [ /* vac1, vac2, ...., vacn */ ];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
You could use eval for the variable name and build an new array with another array for the wanted keys.
Basically you should reorganize yor program to use a solution without eval. An array could help. It is made for iteration.
var x = count.count,
i,
keys = ['vacancy_title', 'vacancy_latlng', 'vacancy_url', 'vacancy_location'],
locations = [];
object;
for (i = 1; i <= x; i++) {
object = eval('vac' + i);
locations.push(keys.map(function (k) { return object[k]; }));
}
Group the vac* elements in an array and then use slice to cut out as many as you want, then use map to generate the result array:
var vacs = [vac1, vac2 /*, ...*/]; // group the vacs into one single array
var x = count.count; // x is the number of vacs to generate
var locations = vacs.slice(0, x).map(function(vac) { // slice (cut out) x elements from the arrays vacs then map the cut-out array into your result array
return [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
});
Because any global variable is a property of the global object :
var vac1 = "whatever";
console.lof(window.vac1); // => logs "whatever"
console.lof(window["vac1"]); // => accessed as an array, logs "whatever" too
You could use the global object and access it as an array to look for your vac1, vac2, vac3 variables :
var x = count.count, i;
locations = [],
array = [],
var globalObject = window; // or whatever the global object is for you
var vac; // this will be used to store your vac1, vac2, etc.
for (i = 0; i < x; i++) {
vac = globalObject["vac"+i]; // the "vac" + i variable read from the global object
if (vac !== undefined) {
array = [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
locations.push(array);
}
}
I have an array of input fields called '$inputFieldsArray' then I slice them to group by 3 into 'newArray' then I need new array value for each item to assign to another array cause in the end I need an array with input fields values grouped by 3. The end goal is to get an array which contains for 9 input fields ex [[i1,i2,i3],[i4,i5,i6],[i7,i8,i9]].
For some reason 'stringArray' output is nothing, first two arrays print correct results. It's probably some mistake I do regarding JS arrays.. Sorry js is not my main language, I try to learn it. Thanks.
Here is a screenshoot with chrome console:
Here is my function:
$($submitButton).click(function () {
// Get number of input fields
let $total = $("input[name^='bodyHeader']").length;
// Get input fields as objects
let $inputFieldsArray = $("input[name^='bodyHeader']");
let newArray = [];
let stringArray = [];
let j = 0;
// Group input fields by 3
for (let i = 0; i < $total - 1; i += 3) {
newArray[j] = $inputFieldsArray.slice(i, i + 3);
j++;
}
// Extract string values from newArray and pass them into stringArray
for (let k = 0; k < newArray.length - 1; k++) {
stringArray[k][0] = newArray[k][0].value;
stringArray[k][1] = newArray[k][1].value;
stringArray[k][2] = newArray[k][2].value;
}
// Print to test results
console.log($inputFieldsArray);
console.log(newArray);
console.log("String Array: " + stringArray);
... // Function logic is not complete
});
SOLUTION:
There is no way to declare dynamic length bidimensional array in js. Use this approach suggested by #Stephan :
stringArray[k] = [newArray[k][0].value, newArray[k][1].value,
newArray[k[2].value];
or this approach suggested by #Lorenzo Gangi:
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
stringArray[k] is undefined because you defined stringArray as [] (Your browser probably threw an exception). Additionally newArray[k] starts at index 0.
You could write stringArray[k] = [newArray[k][0].value, newArray[k][1].value, newArray[k][2].value] instead.
Basically,
stringArray[k]
is undefined yet, therefore setting its [0] property wont work. May do:
stringArray[k] =newArray[k].map(el=>el.value);
Alltogether:
$($submitButton).click(function () {
let stringArray = $("input[name^='bodyHeader']").toArray().reduce((res,_,i,arr)=>((i%3==0 && res.push(arr.slice(i,i+3).map(e=>e.value))),res),[]);
});
here is my javascript:
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
obj = JSON.parse(json);
var arrayobj = obj.GetReportIdResult.length;
alert (arrayobj);
I want to count how many type in the same bulan value, (e.g. there are 3 type = CHEESE1K, UHT, and ESL in bulan = 4)
how to do that?
There's still a typo in your JSON: you've got two commas in a row between the first two "bulan":"6" objects. But assuming you fix that...
If you're asking how to count distinct types for a particular bulan value you can do something like this:
function countTypesForBulan(resultArray, bulanVal) {
var i,
types,
count = 0;
for (i=0, types = {}; i < resultArray.length; i++)
if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
types[resultArray[i].type] = true;
count++;
}
return count;
}
console.log( countTypesForBulan(obj.GetReportIdResult, "4") ); // logs 3
The above loops through the array looking for a particular bulan value, and when it finds one it checks if it has already seen the associated type - if not, it adds it to the types object and increments the counter.
Demo: http://jsfiddle.net/pAWrT/
First of all, put the JSON into a string,
else your example code wont work.
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},,{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
Then,
Iterate with for and count in a variable or a hashmap.
Since GetReportIdResult is an array, you can:
for( var i : obj.GetReportIdResult ){
obj.GetReportIdResult[i] ... // Use at will.
This will give you a map object which will contain the count for each bulan value. For example, map['4'].count will return 3.
var i, row, arr = obj.GetReportIdResult, map = {};
for (i = 0; i < arr.length; i++) {
row = arr[i];
map[row.bulan] = map[row.bulan] || {count: 0};
if (map[row.bulan][row.type] === undefined) {
map[row.bulan][row.type] = row.type;
map[row.bulan]['count'] += 1;
}
}
console.log (JSON.stringify(map));
JSFiddle here.
I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}