This is the json I'm trying to for loop through:
var json = {"series":[
{
"id":1448822,
"name":"Buckinghamshire",
"selected":true,
"data":[
[
19.23,
19.23
]
]
},
{
"id":1448823,
"name":"Cambridgeshire",
"selected":false,
"data":[
[
38.46,
61.54
]
]
}
}
I've been trying to workout how to get the array position with the name selected with value true to the following code:
for (var i = 0; i < json.length; i++) {
var geoAreaSelected = serData[i].selected;
if (geoAreaSelected === true) {
this.series[i].data[i].setState('select');
}
};
EDIT:
var json = {
"series":[
{
"id":1448822,
"name":"Buckinghamshire",
"selected":true,
"data":[[19.23, 19.23]]
},
{
"id":1448823,
"name":"Cambridgeshire",
"selected":false,
"data":[[38.46, 61.54]]
}
] // <= This was missing
};
for (var i = 0; i < json.series.length; i++) {
var geoAreaSelected = json.series[i].selected;
if (geoAreaSelected === true) {
console.log( json.series[i].data[i])
}
};
Console logs [ 19.23, 19.23 ]
You have to iterate over json.series and not over json
for (var i = 0; i < json.series.length; i++) {
var geoAreaSelected = json.series[i].selected;
if (geoAreaSelected === true) {
json.series[i].data[i].setState('select');
console.log(i); // <--- you can use the variable i to access ith object in the array
}
};
Related
I want to filter the multiple attributes with multiple values
'arr' is a list of all products and f_... is the attribute like color or type.
'namet' is the chosen attribute from the user.
'keyt' is the values of each attribute like red, yellow and green.
let arr = [
{ "id": 523, "f_105": ["992","996"], "f_104": ["985"], "f_106":["1000"] },
{ "id": 524, "f_105": ["993","996"], "f_104": ["984"], "f_106":["1001"] }
]
these arrays which user chose for searching
I can get the attrubites like this
var namet = ['f_106', 'f_106', 'f_105', 'f_105', 'f_104' ];
var keyt = ['1000' , '1001', '993', '996', '985'];
OR
var chooenKey = ['f_106', 'f_105', 'f_104']
var chosenAttr = {
"f_106": ["1000", "1001"],
"f_105": ["993", "996"],
"f_104": ["985"],
}
OR
var chosenAttr =
[
{"f_106": ["1000", "1001"]},
{"f_105": ["993", "996"]},
{"f_104": ["985"]}
]
I want a method to loop to get result like variable 'filtered'
var filtered = d =>
(d.f_106.indexOf("1000") > -1 || d.f_106.indexOf("1001") > -1) &&
(d.f_105.indexOf("993") > -1 || d.f_105.indexOf("996") > -1) &&
(d.f_104.indexOf("985") > -1)
then put it here
const f = arr.filter(filtered);
You can also give another type to filter the product with multiple attributes.
If you examine the example I sent, I believe it will solve your problem.
let arr = [
{ "id": 523, "f_105": ["992", "996"], "f_104": ["985"], "f_106": ["1000"] },
{ "id": 524, "f_105": ["993", "996"], "f_104": ["984"], "f_106": ["1001"] }
]
var chosenAttr =
[
{ "f_106": ["1000", "1001"] },
{ "f_105": ["992"] },
{ "f_104": ["985"] }
]
function filterArr() {
var arrCopy = arr;
for (i = 0; i < chosenAttr.length; i++) {
for (var key in chosenAttr[i]) {
arrCopy = arrCopy.filter(function (item) {
var is_match = false;
for (var idx in chosenAttr[i][key]) {
let val = chosenAttr[i][key][idx];
if (item[key].indexOf(val) > -1) {
is_match = true;
}
}
return is_match;
});
}
}
return arrCopy;
}
var filterData = filterArr();
$('#response').html(JSON.stringify(filterData));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
<code id="response">
</code>
</pre>
i have some problem with this work, i plan to create a function to compute from two for () functions. if you ask why I have to make 2 functions to calculate it, it is because the calculated data is taken from different json data, and I need to loops each of those data to get dynamic sum row.
my first function for()
jml_lls_doktor = [
{
"t20181": {
"jum": 5090 //get it jum
}
},
{
"t20191": {
"jum": 3386
}
},
{
"t20201": {
"jum": 1826
}
}
];
let result_doktor = [];
let i = 0;
if(jml_lls_doktor){
for(var key in jml_lls_doktor){
result_doktor[i]={
"jumlah_doktor_hitung" : Object.keys(jml_lls_doktor[key]).map((keys, i9)=>
jml_lls_doktor[key][keys]
)
}
i++;
}
}
console.log(result_doktor);
and this my second function for
let jml_ipk3 = [
{
"2018": {
"ipk2": "null",
"ipk3": "null"
}
},
{
"2019": {
"ipk2": 4,
"ipk3": 4
}
},
{
"2020": {
"ipk2": "null",
"ipk3": "null"
}
}
];
let result_ipk3 = [];
let i2 = 0;
if(jml_ipk3){
for(var key in jml_ipk3){
result_ipk3[i2]={
"ipk3" : Object.keys(jml_ipk3[key]).map((keys, i9)=>
jml_ipk3[key][keys].ipk3
)
}
i2++;
}
}
console.log(result_ipk3);
How i count
(result_ipk3/result_doktor)*100
let count = [];
let i = 0;
for(var key in jml_lls_doktor, jml_ipk3 ){
count [i]={
"ipk3" : Object.keys(jml_lls_doktor[key]).map((keys, i9)=>
parseInt(jml_lls_doktor[key][keys].ipk3)
),
"aktif" : Object.keys(jml_lls_doktor_aktif[key]).map((keys, i9)=>
parseInt(jml_lls_doktor_aktif[key][keys].jum)
)
}
i_count_doktor++;
}
///On rendering reactjs
{
count_doktor.map((list,i)=>
<td style={{textAlign:'center'}}>
{String(list.ipk3/list.aktif*100).slice(0,4)}%
</td>
)
}
I'm trying to run a check against two arrays (one has 4 objects, one just have a few strings) with for loops and if statement for a problem set.
The idea is to use for loop to iterate over every element in the object array and the string array, then use if statement to figure out matches and shove the matching string into a new array. Once all the elements are iterated, it returns the string if there is a matching one.
The problem is the function calls it a day once a single match in the object array is found and returns that only that instead of iterating over the rest of the elements in the object array.
var passengers = [
{ name: ["Michael Jackson"], paid: true },
{ name: ["Osama"], paid: false },
{ name: ["Harambe"], paid: true },
{ name: ["Pepe"], paid: true },
];
var noFlyList = ["Jimmy", "John", "Pepe", "Osama"];
function checkNoFly(passengers, noFlyList) {
for (var i = 0; i < passengers.length; i++) {
for (var j = 0; j < noFlyList.length; j++) {
if (passengers[i].name[0] == noFlyList[j]) {
var passengerList = [];
passengerList.push(passengers[i].name[0]);
return passengerList;
}
}
}
return true;
}
function checkNotPaid(passengers) {
return (!passengers.paid);
}
function processPassenger(passengers, testFunction) {
for (var i = 0; i < passengers.length; i++) {
if (testFunction(passengers[i])) {
return false;
}
}
return true;
}
var allCanFly = processPassenger(passengers, checkNoFly);
if (!allCanFly) {
console.log("We cannot fly because " + checkNoFly(passengers, noFlyList) + " is on the no-fly list");
}
var allPaid = processPassenger(passengers, checkNotPaid);
if (!allPaid) {
console.log("we cannot fly because not all passengers have paid");
}
use this: having passengerList in the loop make its reinitialized to empty array on each loop, and returning passengerList in the loop makes the loop break once it finishes the first loop
function checkNoFly(passengers, noFlyList) {
var passengerList = [];
for (var i = 0; i < passengers.length; i++) {
for (var j = 0; j < noFlyList.length; j++) {
if (passengers[i].name[0] == noFlyList[j]) {
passengerList.push(passengers[i].name[0]);
}
}
}
return passengerList;
}
EDIT:
change your original processPassenger function to the one below, originally you have only 1 argument passed to your checkNoFly function, where you'd defined it to take 2 arguments, so the false is returned for wrong number of argument, which stop you from getting it the way you want.
function processPassenger(passengers, testFunction) {
if (testFunction(passengers, noFlyList).length !=0) {
return false;
}
return true;
}
EDIT 2: for your updated question, since for the first check we are returning an array for the single function processPassenger() for validation, we can take similar approach for the checkNotPaid function to return an array for those who have not paid.
function checkNotPaid(passengers) {
var passengerNotPaid = [];
for (var i = 0; i < passengers.length; i++) {
if (!passengers[i].paid) {
passengerNotPaid.push(passengers[i].name[0]);
}
}
return passengerNotPaid;
}
unless you'd want to refactor everything, i think this would be ok.
You're telling it to do so: return passengerList; in your inner loop. Also, you keep re-declaring the variable var passengerList = []; inside your inner for-loop, emptying it every time.
var passengers = [
{ name: ["Michael Jackson"], paid: true },
{ name: ["Osama"], paid: false },
{ name: ["Harambe"], paid: true },
{ name: ["Pepe"], paid: true },
];
var noFlyList = ["Jimmy", "John", "Pepe", "Osama"];
function checkNoFly(passengers, noFlyList) {
var passengerList = [];
for (var i = 0; i < passengers.length; i++) {
for (var j = 0; j < noFlyList.length; j++) {
if (passengers[i].name[0] == noFlyList[j]) {
passengerList.push(passengers[i].name[0]);
}
}
}
return passengerList;
}
function checkNoPay(passengers) {
var nonPayers = [];
for (var i = 0; i < passengers.length; i++) {
if (!passengers[i].paid) { nonPayers.push(passengers[i].name); }
}
return nonPayers;
}
var banList = checkNoFly(passengers, noFlyList);
if (banList.length) {
console.log("We cannot fly because " + banList + " is/are on the no-fly list");
}
var unpaidList = checkNoPay(passengers);
if (unpaidList.length) {
console.log("We cannot fly because " + unpaidList + " has/have not payed the flight");
}
var canWeFly = !(banList.length || unpaidList.length);
console.log(canWeFly ? "We can fly" : "We cannot fly");
If I have a JavaScript object like this:
{"products":
[
{
"id":"6066157707315577",
"reference_prefix":"BB",
"name":"BeanieBaby",
"product_line":false,
"has_ideas":true
},
{
"id":"6066197229601550",
"reference_prefix":"BBAGS",
"name":"BlackBags",
"product_line":false,
"has_ideas":false
}
],
"pagination": {
"total_records":4,
"total_pages":1,
"current_page":1
}
}
How do I write a function in js to loop over each pair and only return the elements of the array where has_ideas === true?
I have started with this but I'm stuck. Clearly I am new to this. Any help appreciated.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
if (json[i].id === "has_ideas" && json[i].value === true) {
return json;
}
return [];
}
}
You can filter out each pair by simply checking that property:
var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}
var stuff = json.products.filter(function(obj) {
return obj.has_ideas === true
});
console.log(stuff);
Demo:http://jsfiddle.net/bsyk18cb/
try this
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if(json[i].has_ideas === true){
return json;
}
return [];
}
}
You want to check the "has_ideas" attribute and if true, return the id.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if (json[i].has_ideas === true) {
return json[i].id;
}
return [];
}
}
Use code below.
this will return array of elements having has_ideas=true
var json = "{'products':"+
"["+
"{"+
"'id':'6066157707315577',"+
"'reference_prefix':'BB',"+
"'name':'BeanieBaby',"+
"'product_line':false,"+
"'has_ideas':true"+
"},"+
"{"+
"'id':'6066197229601550',"+
"'reference_prefix':'BBAGS',"+
"'name':'BlackBags',"+
"'product_line':false,"+
"'has_ideas':false"+
"}"+
"],"+
"'pagination': {"+
"'total_records':4,"+
"'total_pages':1,"+
"'current_page':1"+
"}"+
"}";
function filter(){
var jsonArr = [];
var gList = eval( "(" + json + ")");
alert(gList.products.length);
for(var i=0;i<gList.products.length;i++){
if(gList.products[i].has_ideas){
jsonArr.push(gList.products[i]);
}
}
return jsonArr;
}
Demo
Say I have this JSON:
[
{
"ID": "1",
"title": "Title 1",
},
{
"ID": "2",
"title": "Title 2",
}
]
How would I return the set of key names that recur for each record? In this case, ID, title.
I tried:
$.getJSON('testing.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key +', ');
});
$('<p/>', {
html: items.join('')
}).appendTo('#content');
});
without success.
This is a JSON "database", and every "record" has the same keys. I just want a script that will tell me what the keys are, not test whether or not they occur in every entry.
This will give you an array of all the string properties that match across an array of objects. Is that what you are looking for?
$.getJSON('testing.json', function(data) {
var propertiesThatExistInAll = getPropertiesThatExistInAll(data);
});
var getPropertiesThatExistInAll = function(arr) {
var properties = $.map(data[0], function (prop, value) {
return prop;
});
var propertiesThatExistInAll = [];
$.each(properties, function (index, property) {
var keyExistsInAll = true;
// skip the first one since we know it has all the properties
for (var i = 1, len = data.length; i < len; i++) {
if (!data[i].hasOwnProperty(property)) {
keyExistsInAll = false;
break;
}
}
if (keyExistsInAll) {
propertiesThatExistInAll.push(property);
}
});
return propertiesThatExistInAll;
};
Something like this, perhaps?
items = [];
for (key in jsonobj) {
if (!itemExists(items, key)) {
items[items.length] = key
}
}
function itemExists(items, value) {
for (i = 0; i < items.length; i++) {
if (items[i] == value) {
return true
}
}
return false;
}
Of course, that will return items that exist in any one of the objects, not that exist in all. It's not entirely clear from your question if this is the solution you want.
This can probably be made more efficient/concise, but the function below will do it.
var testJson = [ {'oi' : 1, 'arf': 2, 'foo' : 0}, {'oi': 5, 'arf': 7}];
function commonKeys(j)
{
var fillUp = [];
for(var i in j[0])
fillUp.push(i);
for(var i = 1; i < j.length; i++)
{
var cur = j[i]; var curArr = [];
for (var i in cur) {curArr.push(i)};
fillUp = fillUp.filter(function(x) {return (curArr.indexOf(x) != -1);});
}
return fillUp;
}
alert(commonKeys(testJson)); //oi,arf (not foo)