Loop through array of objects and check conditions - javascript

I have an array of object like this
list = [
{
"label" : "whatever",
"value" : "value 1"
},
{
"label" : "whatever",
"value" : "value 2"
},
{
"label" : "Required scenario only",
"value" : "value 3"
},
{
"label" : "whatever",
"value" : "value 4"
},
]
I am running for a loop with conditions, I want to execute some piece of code only for one scenario called 'Required scenario only' for the rest of all scenarios run different code for only one time, it should not execute 3 times as per loop executes
for(i=0; i< list.length; i++) {
if(list[i].label === 'Required scenario only' ) {
//execute some code
} else {
// execute code for 1 time for rest of the labels i.e for all 'whatever' scenarios
}
}
How should I do it?

If you're merely checking for the existence of an object with label = "Required scenario only" then I would use Array.some():
list = [{
label: "whatever",
value: "value 1"
},
{
label: "whatever",
value: "value 2"
},
{
label: "Required scenario only",
value: "value 3"
},
{
label: "whatever",
value: "value 2"
},
]
if (list.some(l => (l.label == "Required scenario only"))) {doSomething();}
else {doSomethingElse();}
function doSomething() {console.log("Do Something");}
function doSomethingElse() {console.log("Do Something Else");}

Related

How to combine data from an array and object and put together into an array in JavaScript?

I have an array in which I have some string value holding the id along with answer selected and I have different object in which I have the detail about answer which is selected. The below array keep updated whenever we select an option from question.
arr = ["Q1A1", "Q2A3"]
assume Q1 is Question no. 1 and A1 is option selected from the question. And below I have an object for the corresponding Q1 which contained the detail about answers and this object also get change as we move over to Q2
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
}
same way I have any another object for Q2 if we select the answer in Q1, now we have different object for Q2
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
I need to lookup the object with the help of array which contain question and answer(eg, "Q1A1") with selected and need to find the text for answer selected i.e ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.
result = ["Q1_Yes","Q2_Test3"]
This code will help you to get those results.
let selected = ["Q1A1", "Q2A3"];
let QA = [
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
},
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
];
let all_answers = QA.reduce((allanswers,qa)=>(qa.answers.map(d=> allanswers[d.id]=[qa.id,d.text]),allanswers),{});
const result = selected.map(selected => all_answers[selected].join('_'))
console.log(result)

Mongodb mapreduce Join 2 collections

I have 2 collections and I am new to Mongo MapReduce concept.
My collection Value looks like this
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb7"),
"name" : "Title 1",
"value" : "value 1 for title 1"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb8"),
"name" : "Title 1",
"value" : "Value 2 for title1. "
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccb9"),
"name" : "Title 2",
"value" : " Definitely a motivational text!"
}
{
"_id" : ObjectId("5bc4f20e1a80d2045029ccba"),
"name" : "Title 2",
"value" : "It's tough but I'm carrying on. "
}
Other collection Details look like:
{
"_id" : ObjectId("5bc4f2361a80d2045029d05b"),
"name" : "Title 1",
"totalValues" : 6.0000000000000000,
"link": "Link1",
"description" : "Some More Text to Make title 1 look better"
}
{
"_id" : ObjectId("5bc4f2361a80d2045029d2eb"),
"name" : "Title 2",
"totalValues" : 2,
"link": "Link2",
"description" : "Some More Text to Make title 2 look better"
} ...
I want the output result as
{
“name” : “XXXXXXXX”,
“comments” : [ {“value”: “XXXXXXX”}, {“value”: “YYYYYYYY”}],
“totalValues” : 2,
“link”: “XXXXXXXXXX”,
“description”: “XXXXXXXXXXXXXXXXXX”
}
with the following output document. Please help.
I have tried following code:
var mapDetails = function(){
var output = {name: this.name,totalValues :this.totalValues, description : this.description, link :this.link}
emit(this.name, output);
};
var mapGpas = function() {
emit(this.name,{name:this.name, value:this.value, totalValues:0, description: 0, link: 0});
};
var r = function(key, values) {
var outs = { name: 1,value: 1, description: 0,totalValues:0, link: 0};
values.forEach(function(v){
outs.name = v.name;
if (v.value == 0) {
outs.description = v.description;
outs.totalValues = v.totalValues;
outs.link = v.link;
}
});
return outs;
};
res = db.Value.mapReduce(mapGpas, r, {out: {reduce: 'joined'}})
res = db.Details.mapReduce(mapDetails, r, {out: {reduce: 'joined'}})
db.joined.find().pretty()

find in mongoDB documents with filled nested array and build new result object

I have some document with this structure - the category field can also be empty
{
"_id" : "1",
"category" : [
{ "target" : "element 1" },
{ "target" : "element 2" }
]
},
{
"_id" : "2",
"category" : [
{ }
]
},
{
"_id" : "3",
"category" : [
{ "target" : "element 1" },
{ "target" : "element 2" }
]
},
What I need is a result like
{ id: 1, element: "element 1" },
{ id: 1, element: "element 2" },
{ id: 3, element: "element 1" },
{ id: 3, element: "element 2" }
That means first I have to check for all documents which have target elements:
var result = db.collection.find({}, { 'category.target': 1})
1) But this doesn't work, as I still get the empty doc (2).
2) Second I need to get a new result element for each element in the target-array. I think aggregate isn't the correct way as there has to be new objects for each element. And map is only to nave the fields.
So I think I have to iterate over the results and build a new object, correct?
result.forEach(function($res){
// do a new foreach for every element in target-array?
newResult.push({ id: res._id, element: res.element });
});
You can do this using aggregate which, unlike find, allows you to reshape documents.
db.test.aggregate([
// Duplicate each doc, once per category element
{$unwind: '$category'},
// Reshape the documents to create the element field
{$project: {element: '$category.target'}},
// Only include docs with an element
{$match: {element: {$exists: true}}}
])
Result:
"result" : [
{
"_id" : "1",
"element" : "element 1"
},
{
"_id" : "1",
"element" : "element 2"
},
{
"_id" : "3",
"element" : "element 1"
},
{
"_id" : "3",
"element" : "element 2"
}
]

Creating relationships between items in a Knockout.js model

jsFiddle: http://jsfiddle.net/brandondurham/g3exx/
How can I create relationships between various observableArrays in my model? For instance, in my model I have a cartItems array, and each item in that array has a nested itemFreebies array as well as an itemType property. Customers only get free items when they have a subscription in their cart ("itemType" : "subscription") and, as such, when that subscription is removed I need to remove all other cart items' freebies, preferably with a nice fadeOut animation.
What is the best way to create these types of conditional relationships?
This is the object I'm using in my model:
{
"cartItems" : [
{
"itemName" : "Product 1",
"itemDesc" : "Product 1 description",
"itemType" : "subscription",
"itemPrice" : 299,
"itemFreebies" : false
}, {
"itemName" : "Product 2",
"itemDesc" : "Product 2 description",
"itemType" : "desktop",
"itemPrice" : 4499,
"itemFreebies" : [{
"freebieName" : "Product 2 freebie",
"freebieDesc" : "Product 2 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 3",
"itemDesc" : "Product 3 description",
"itemType" : "desktop",
"itemPrice" : 8999,
"itemFreebies" : [{
"freebieName" : "Product 3 freebie",
"freebieDesc" : "Product 3 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 4",
"itemDesc" : "Product 4 description",
"itemType" : "desktop",
"itemPrice" : 99,
"itemFreebies" : [{
"freebieName" : "Product 4 freebie",
"freebieDesc" : "Product 4 freebie description",
"freebieOriginalPrice" : 99
}]
}, {
"itemName" : "Product 5",
"itemDesc" : "Product 5 description",
"itemType" : "webfont",
"itemPrice" : 49,
"itemFreebies" : false
}
]
}
I would start with something like this:
$(function () {
​var CartViewModel = {
var self = this;
self.cartItems = ko.observableArray([]);
self.eligibleForFreebies = ko.computed(function() {
return ko.utils.arrayFirst(self.cartItems(), function(cartItem) {
// I forgot the () after itemType in the original post
return (cartItem.itemType() === 'subscription');
});
// Note: ko.utils.arrayFirst will either return the item in
// question, or it will return undefined or null…
// I forget which, but either will result in
// eligibleForFreebies evaluating to false
});
};
var Product = function() {
var self = this;
self.itemName = ko.observable();
self.itemDesc = ko.observable();
self.itemType = ko.observable();
self.itemPrice = ko.observable();
self.itemFreebies = ko.observableArray([]);
};
var Freebie = function() {
var self = this;
self.freebieName = ko.observable();
self.freebieDesc = ko.observable();
self.freebieOriginalPrice = ko.observable();
}
ko.applyBindings(new CartViewModel());
// load data
});
​
Load Products into the cartItems observableArray in the CartViewModel.
The dependent observable (ko.computed) value eligibleForFreebies will determine whether or not the Freebies should be allowed.
It's likely that you wouldn't even need to remove the freebies from the Products when the cart is not eligible for them – simply check eligibleForFreebies and include or exclude the freebies from the display, invoice, etc. (This might save you the headache of retrieving freebies after the user adds the subscription, but I suppose that depends on your scenario.)
Hope this helps to get you started on this one, but let me know if you have any questions.
UPDATE: I forked your fiddle and reworked your code a bit... well, I mostly moved it around, but I did add some functionality.
Notice that if you delete the subscription item from the cart, all the freebies disappear from the cart display--but I didn't delete them from the objects!
If one adds a method for re-adding a subscription item to the cart, the freebies would reappear.
Please have a look when you have a chance, and let me know if you'd like me to explain anything.

Complex JSON nesting of objects and arrays

I am having difficultly with syntax and structure of JSON objects/arrays.
{
"accounting" : [
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 },
{ "firstName" : "Mary",
"lastName" : "Smith",
"age" : 32 }
],
"sales" : [
{ "firstName" : "Sally",
"lastName" : "Green",
"age" : 27 },
{ "firstName" : "Jim",
"lastName" : "Galley",
"age" : 41 }
]
}
I want to make a nested structure of objects and arrays that would house the following info:
{
"problems": [{
"Diabetes":[{
"medications":[{
"medicationsClasses":[{
"className":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}],
"className2":[{
"associatedDrug":[{
"name":"asprin",
"dose":"",
"strength":"500 mg"
}],
"associatedDrug#2":[{
"name":"somethingElse",
"dose":"",
"strength":"500 mg"
}]
}]
}]
}],
"labs":[{
"missing_field": "missing_value"
}]
}],
"Asthma":[{}]
}]}
But I have no idea what the right way to do this should be. Should I just be making JavaScript objects? Does JSON make sense for this project?
What is the correct syntax to set something like this up?
Here is my code so far:
$(document).ready(function() {
$.getJSON('js/orders.json', function(json) {
$.each(json.problems, function(index, order) {
$('.loadMeds').append('<p>' + order.name + '</p>')
});
});
});
The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword
You don't have any comments in your JSON, but you should remove the var and start like this:
orders: {
The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:
"associatedDrug": {
"name":"asprin",
"dose":"",
"strength":"500 mg"
}
Also, the empty object labs should be filled with something.
Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)
Update 2 answered:
obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name
returns 'aspirin'. It is however better suited for foreaches everywhere
I successfully solved my problem. Here is my code:
The complex JSON object:
{
"medications":[{
"aceInhibitors":[{
"name":"lisinopril",
"strength":"10 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"antianginal":[{
"name":"nitroglycerin",
"strength":"0.4 mg Sublingual Tab",
"dose":"1 tab",
"route":"SL",
"sig":"q15min PRN",
"pillCount":"#30",
"refills":"Refill 1"
}],
"anticoagulants":[{
"name":"warfarin sodium",
"strength":"3 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"betaBlocker":[{
"name":"metoprolol tartrate",
"strength":"25 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"diuretic":[{
"name":"furosemide",
"strength":"40 mg Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}],
"mineral":[{
"name":"potassium chloride ER",
"strength":"10 mEq Tab",
"dose":"1 tab",
"route":"PO",
"sig":"daily",
"pillCount":"#90",
"refills":"Refill 3"
}]
}
],
"labs":[{
"name":"Arterial Blood Gas",
"time":"Today",
"location":"Main Hospital Lab"
},
{
"name":"BMP",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"BNP",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"BUN",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Cardiac Enzymes",
"time":"Today",
"location":"Primary Care Clinic"
},
{
"name":"CBC",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Creatinine",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"Electrolyte Panel",
"time":"1 Year",
"location":"Primary Care Clinic"
},
{
"name":"Glucose",
"time":"1 Year",
"location":"Main Hospital Lab"
},
{
"name":"PT/INR",
"time":"3 Weeks",
"location":"Primary Care Clinic"
},
{
"name":"PTT",
"time":"3 Weeks",
"location":"Coumadin Clinic"
},
{
"name":"TSH",
"time":"1 Year",
"location":"Primary Care Clinic"
}
],
"imaging":[{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
},
{
"name":"Chest X-Ray",
"time":"Today",
"location":"Main Hospital Radiology"
}
]
}
The jQuery code to grab the data and display it on my webpage:
$(document).ready(function() {
var items = [];
$.getJSON('labOrders.json', function(json) {
$.each(json.medications, function(index, orders) {
$.each(this, function() {
$.each(this, function() {
items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
});
});
});
$('<div>', {
"class":'loaded',
html:items.join('')
}).appendTo("body");
});
});
Make sure you follow the language definition for JSON. In your second example, the section:
"labs":[{
""
}]
Is invalid since an object must be composed of zero or more key-value pairs "a" : "b", where "b" may be any valid value. Some parsers may automatically interpret { "" } to be { "" : null }, but this is not a clearly defined case.
Also, you are using a nested array of objects [{}] quite a bit. I would only do this if:
There is no good "identifier" string for each object in the array.
There is some clear reason for having an array over a key-value for that entry.
First, choosing a data structure(xml,json,yaml) usually includes only a readability/size problem. For example
Json is very compact, but no human being can read it easily, very hard do debug,
Xml is very large, but everyone can easily read/debug it,
Yaml is in between Xml and json.
But if you want to work with Javascript heavily and/or your software makes a lot of data transfer between browser-server, you should use Json, because it is pure javascript and very compact. But don't try to write it in a string, use libraries to generate the code you needed from an object.
Hope this helps.
You can try use this function to find any object in nested nested array of arrays of kings.
Example
function findTByKeyValue (element, target){
var found = true;
for(var key in target) {
if (!element.hasOwnProperty(key) || element[key] !== target[key]) {
found = false;
break;
}
}
if(found) {
return element;
}
if(typeof(element) !== "object") {
return false;
}
for(var index in element) {
var result = findTByKeyValue(element[index],target);
if(result) {
return result;
}
}
};
findTByKeyValue(problems,{"name":"somethingElse","strength":"500 mg"}) =====> result equal to object associatedDrug#2

Categories