Find index of filtered array - javascript

I have a JSON object which looks like this:
var JSON = {
"implants":[{
"familyId": "3",
"reference": "1234",
"quantity": "3"
},{
"familyId": "2",
"reference": "3456",
"quantity": "1"
}]
}
I'm building a function which searches whether an implant with the given "reference" is already in the array. If it's not, it just gets added to the array. Easy. If it is in the array, then I want to add the new quantity to the existing quantity and then update the array.
function returnTheseImplantsWhere(key1,key2){
return function(el){
if(el[key1]==key2) {
return el;
}
}
}
var activeCaseImplants = JSON.parse(getLocal("activeCaseImplants"));
var existingImplant = activeCaseImplants.implants.filter(returnTheseImplantsWhere("reference", window.currentImplantRef));
if(existingImplant.length) {
//previously added implant
newImplantQty = Number(existingImplant[0].quantity) + Number($("#qty").val());
existingImplant.quantity = newImplantQty;
} else {
//new implant
}
My question relates to the "previously added implant" section of the above code (which all works as expected). I now have the updated quantity, but I can I determine which object within the activeCaseImplants.implants array needs it's quantity updated? I feel like I could make use of indexOf somewhere around the line beginning with var existingImplant = ... but I'm not sure where or how. Any ideas?

Related

How to create json array of object if the key already exist

I'm a beginner with JavaScript and query. I have an html form where the user can add or remove a group of fields. The group of fields contains 1 select and 3 inputs. The group of fields added have the same name of the previouses and so on.
What I'm trying to do is retrieve the value creating a structure like this.
{
"colture1": [{
"code_app": "A2",
"long": "1",
"lat": "103"
}, {
"code_app": "B34",
"long": "11",
"lat": "12"
}],
"colture2": [{
"code_app": "GH3456",
"long": "55",
"lat": "90"
}]
// ....and so on
}
If the user selects a colture that already exist in the object, I'd like to add the others value in the same key as you can see in "colture1". My problem is here, I can't create an array where I can add the others value, now my function override the preovious values, It writes the last one values and it doesn't create an array.
This is my function
$('#create_json').on("click", function(e) {
const json_data = {};
var cat = "";
for (const input of document.querySelectorAll(".card[mainBlock] select, .card[mainBlock] input")) {
if (input.tagName === 'SELECT') {
cat = input.value;
} else {
(json_data[cat] = json_data[cat] || {})[input.name] = input.value;
}
}
console.log(JSON.stringify(json_data));
})
Here I can put a demo here https://jsfiddle.net/ou7h4f2m/3/. Thank you in advance
It is probably easier if you would deal with one section in each outer loop iteration (just on .card[mainBlock]), and then use an inner loop for processing the category and properties:
$('#create_json').on("click", function (e) {
const data = {};
for (const section of document.querySelectorAll(".card[mainBlock]")) {
const cat = section.querySelector("select").value;
const obj = Object.assign(...Array.from(section.querySelectorAll("input"), input =>
({ [input.name]: input.value })
));
(data[cat] = data[cat] || []).push(obj);
}
console.log(JSON.stringify(data));
});
I would not call your main variable json_data. It does not represent JSON, but a JavaScript object. JSON is what you get from calling JSON.stringify.

How to remove character from left of the string until first : if found?

I have JSON String as the one below which is returned from the previous function. It is a string, not object.
{
"qs1": {
"mistake": [{
"id": 1,
"name": "Subject-Verb Agreement Errors."
}, {
"id": 1,
"name": "Sentence Fragments."
}, {
"id": 1,
"name": "Missing Comma After Introductory Element."
}]
}
}
I converted it into an object by using Jquery.parseJSON() now I want to use length to find a number of mistakes.
Problem:
the first key qs1 of the returned JSON can be different like qs2,qs3 & so on. I don't want to use a loop to get the key name qs1,qs2 because it will take a lot of time in only getting a key name and if I have a lot of questions. Also, I don't know the number of questions.
Is there is any way to check qs1.mistake.length>0 without knowing the key name(qs1).
Below is my function:
function SelectiMstake(value) {
alert(value);
var value2 = jQuery.parseJSON(value);
var NewHtml="";
if(value2.mistake.length>0) {
alert("mistake found");
//for(var mistakei = 0; mistakei < value2.mistake.length; mistakei++) {
// NewHtml+= "<input type='check' value='"+ value2.mistake[mistakei] +"'>"+ value2.mistake[mistakei] +"<br>";
// }
//$("#DisplayMistakes").html(NewHtml);
} else {
alert("No mistakes found in the following Question");
}
}
if there is no way I want to stick with my question part when I get JSON string then I want to remove {"qs1": from the start of the string and } from the last. Don't use a character to remove from the start otherwise {"qs12": this will give the wrong result.
Use Object.values(), and just select the first element, or loop through the values (Which is now an array), if you want to check each qs*:
var json = '{"qs1":{"mistake":[{"id":1,"name":"Subject-Verb Agreement Errors."},{"id":1,"name":"Sentence Fragments."},{"id":1,"name":"Missing Comma After Introductory Element."}]}}';
var parsed = JSON.parse(json);
var vals = Object.values(parsed);
console.log(vals[0]);
console.log(vals[0].mistake.length); // 3

for-in loop to for loop or forEach

Ok I have the following scenario. I need to convert this for-in loop to either a for loop or forEach. I have tried a few different examples but can't seem to get the code to append to the page. The for-in loop will work however for the code I need to write, it is not allowed.
This is an example variable
var work = {
"jobs": [{
"employer": "Java",
"title": "Script",
"dates": "2017",
"description": "description",
}
}
This is the code that I have to work. Currently in a for-in loop but need it into a for or forEach loop.
function displayWork() {
for (job in work.jobs) {
//create new div for work experience
$("#workExperience").append(HTMLworkStart);
//concat employer and title
var formattedEmployer = HTMLworkEmployer.replace("%data%",
work.jobs[job].employer);
var formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[job].title);
var formattedEmployerTitle = formattedEmployer + formattedTitle;
$(".work-entry:last").append(formattedEmployerTitle);
var formattedDates = HTMLworkDates.replace("%data%", work.jobs[job].dates);
$(".work-entry:last").append(formattedDates);
var formattedDescription = HTMLworkDescription.replace("%data%",
work.jobs[job].description);
$(".work-entry:last").append(formattedDescription);
});
}
displayWork();
It looks like you will have an array of jobs inside the work object, although your example is missing the closing square bracket for the jobs array, and it might be clearer if you had more than one entry in the array.
Given a data structure like this:
var work = {
jobs: [
{
employer: "example1"
},
{
employer: "example2"
},
{
employer: "example3"
}
]
}
You can use a simple for loop based on the fact that the jobs array will have consecutive integer keys starting at zero:
for (var i = 0; i < work.jobs.length; i++) {
// do stuff with current job in work.jobs[i]
var current_employer = work.jobs[i].employer;
}

How to not proceed with adding a value if its an empty/null string?

My code reads data somewhere and then adds them as values to properties in an object. I made a for loop to iterate over the items in the list so they can each belong in their own cute little object but here is a problem: sometimes there's no value to a property and I wan't to know what I can do to intercept that before it finishes being declared to the property. Maybe replace the empty string with a word or something.
Here is an example code and lets say the title on iteration #3 is going to be an empty "" string. how do I intercept that?
var counter = 0;
for (var i = 0; i < nyData.results.length; i++) {
if (_.indexOf(uniqueItems, nyData.results[i].id)) {
continue;
}
if (!_.indexOf(uniqueItems, nyData.results[i].id)) {
var index = i;
counter++;
let putParams = {
TableName: "Articles",
Item: {
"title": nyData.results[i].title,
"date": nyData.results[i].published_date,
"abstract": nyData.results[i].abstract,
"source": nyData.results[i].source,
"views": nyData.results[i].views,
"author": nyData.results[i].byline,
"section": nyData.results[i].section,
"category": nyData.results[i].des_facet,
"organizations": nyData.results[i].org_facet,
"people_involved": nyData.results[i].per_facet,
"country_subject": nyData.results[i].geo_facet,
"id": nyData.results[i].id,
}
}
db.put(putParams, function(err) {});
}
}
console.log(`Total of ${counter} new articles were inserted into database.`);
callback(null);
if( myVar) {
}
will only be true, if the variable is not:-
Empty
Null
undefined
0
false
....and a few more.

jQuery object get value by key

How would you get the value of assocIMG by key matching the key eg
if I have a var 11786 I want it to return media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
You can use bracket notation to get object members by their keys. You have the variable prods containing a string ("11786"), and the object assocIMG with various keys. Then just use
assocIMG[prods]
to get the property value 'media/catalog/product/8795139_633.jpg' which is associated with that key.
Note that you should always use strings as keys in your object literal, IE does not support numbers there:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Another improvement to your script would be not to loop through the spConfig.attributes each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
You should not use numbers as object keys (in their start). If you want to get the value associated with the 11786 integer key, you will need to use this syntax:
assocIMG["11786"] or assocIMG[11786]
Not
assocIMG.11786
The first thing that you need to do is to create your keys as strings, since you would have:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg',
}
But even doing this, you won't be able to access the field using assocIMG.11786 and the first valid sintax that I presented will still work. The correct approach would be:
var assocIMG = {
id11786: 'media/catalog/product/8795139_633.jpg',
id11787: 'media/catalog/product/8795139_633.jpg',
}
Or
var assocIMG = {
"id11786": 'media/catalog/product/8795139_633.jpg',
"id11787": 'media/catalog/product/8795139_633.jpg',
}
Note that the keys are now starting with letters, not numbers. And now, you will can access the 11786 field as assocIMG.id11786 or assocIMG["id11786"], not assocIMG[id11786]
To Get the Value from object by matching key I ended up with the following
$.each(assocIMG, function(index, value) {
if(index == prods) {
var image_path = value;
$("#product_img").attr("src", image_path);
//alert(image_path);
}

Categories