Looping through jQuery objects - javascript

I've got an associative array with jQuery objects that I want to loop over to set a value on each.
I'm relatively new to JavaScript / jQuery, but this is what I tried without any luck:
var inputs = [
{ key: "firstName", val: $("#signup input[name=firstName]") },
{ key: "lastName", val: $("#signup input[name=lastName]") },
{ key: "email", val: $("#signup input[name=email]") },
{ key: "confirmationEmail", val: $("#signup input[name=confirmationEmail]") },
{ key: "password", val: $("#signup input[name=password]") },
{ key: "terms", val: $("#signup input[name=terms]") }
];
inputs.each(function() {
$(this).val("test");
});

In newer browsers you don't need jQuery for that:
inputs.forEach(function(input) {
console.log("key is " + input.key);
input.val.val("test");
});
The .forEach() method is built-in. If you must use jQuery.s.each()` it'd look like this:
$.each(inputs, function(index, input) {
console.log("key is " + input.key);
input.val.val("test");
});
Note that the jQuery $.each() calls the callback function with the index of the element as the first argument and the element itself as the second. The native .forEach() passes those in reverse order.
Finally just as a note, you can set all the <input> values under the "signup" element with
$("#signup input").val("test");

Try this:
$.each(inputs, function(){ $(this).val("test")});

Related

react adding new array method to return array's object item by it's key

I have some enum objects and i want to get its lebel by it's value.
Let's say this is my enum list
const enumList = {
businessType: [
{ value: "b", label: "B2B" },
{ value: "s", label: "SAAS" },
{ value: "c", label: "C2C" },
],
userType: [
{ value: "A", label: "Admin" },
{ value: "s", label: "Super User" },
{ value: "t", label: "trainer" },
]
}
So now I want to get a particular object label by its key.
like this,
enumList.userType.getLabel('s')'
// super user
I mean, i want to make it re-usable, currently i am doing like this and i dont like it
index = enumList.userType.findIndex(x => x.value ==="s");
enumList.userType[index].label
// super user
Does anyone know how can i make it re-usable to access it from globally like this enumList.userType.getLabel('s) ?
This custom Array method will allow you to do this enumList.userType.getLabel('s') and receive 'Super User'
Array.prototype.getLabel = function(val) {
return this.find(({value}) => value === val).label
}
See Why is extending native objects a bad practice?
It looks like you want a one-liner, so just use find
const { label } = enumList.userType.find(userType => userType.value === 's');

Return true if an array within an array contains specific key

I have the following the object:
items: [
{
object_a {
id: "1",
value: "somevalue1"
}
},
{
object_b {
id: "2"
value: "somevalue2"
items:[
{
nested_object_a {
id: "3"
value: "somevalue3"
},
nested_object_b {
id: "4"
value: "somevalue4"
},
}
]
}
},
]
I can check if the value key exists in the initial items array:
items.some(item => item.hasOwnProperty("value"));
To see if the value key exists in the nested object_b item array I can do the following:
items[1].object_b.items.some(item => item.hasOwnProperty("value"));
Instead of specifying which number in the array to look in I need to make the final expression dynamic. I'm certain I need to do a find or a filter on the top level items, but I've had no luck with it so far.
I found that using an every function on the items allowed me to return the boolean value I required form the array. The problem this created is any array item that didn't have the object_b key on was returning null and breaking my app. It turns out I needed to use an optional chaining operator to get around this (.?).
Thanks to #ikhvjs for linking that stackedoverflow article.
Working code:
items.every(item => {
item.object_b?.items.some(item => item.hasOwnProperty("value"));
});

Find out if an object already exists in an array

I want to do a database operation only if my barcode is new to the structure.
My plan was either to use the function includes() or simply count the existence in the array.
I have found quite helpful code snippets like countDuplicate and the function include() to do the job but I guess my case is a little bit more specific.
But I not only have an object/array which consists of strings. (1st example)
I have an object which includes different objects and their properties.
//1st example (this works pretty well)
function countDuplicate(array, elem) { //just the special type of syntax for Vue/Node.js
return array.filter(item => item == elem).length;
}
var cars = ["Saab", "Volvo", "BMW", "BMW", "BMW"];
console.log(countDuplicate(cars, "BMW"); //will return 3
console.log(cars.includes("BMW")); //will return true
But as I said I have more a structure like that:
var object = {
sub_object1: { title: "test1", barcode: "0928546725" },
sub_object2: { title: "test2", barcode: "7340845435" },
};
How can I get the same results there?
My plan was to do it like that:
if(countDuplicate(object, "0928546725") == 0)
//... do my operations
But this not work because I don't really understand how I get into the structure of my objects. I experimented with different loops but nothing actually worked.
This is my array:
export default {
data() {
return {
form: {
items: [ //Barcodes
],
status: 1,
rent_time: Date.now()
},
submit: false,
empty: false,
}
},
____________________________________________________________________
Solutions:
I tried the following from #adiga and it works for the example but not for my real case.
This is a screen of my console:
So
A simple object.filter(a => a.barcode == elem) should work - #adiga
Like that?
countDuplicateBarcodes: function(obj, elem) {
//return Object.values(obj).filter(a => a.barcode == elem).length;
return obj.filter(a => a.barcode == elem).length;
}
Doesn't work anymore...
Get all the values of object in an array usingObject.values and then use filter
function countDuplicateBarcodes(obj, elem) {
return Object.values(obj).filter(a => a.barcode == elem).length;
}
const object = {
sub_object1: { title: "test1", barcode: "0928546725" },
sub_object2: { title: "test2", barcode: "7340845435" },
sub_object3: { title: "test3", barcode: "0928546725" }
};
console.log(countDuplicateBarcodes(object, "0928546725"))
If you just want to find a barcode in your object, then your question is a duplicate of for example
https://stackoverflow.com/a/46330189/295783
Changed to match you requirement:
const barcodes = {
sub_object1: { title: "test1", barcode: "0928546725" },
sub_object2: { title: "test2", barcode: "7340845435" },
};
const findMatch = (barcode, barcodes) => JSON.stringify(barcodes).includes(`"barcode":"${barcode}"`);
console.log(
findMatch("0928546725",barcodes)
)
Looking at your code, it appears like you actually use an array of objects and not a nested object. If that's the case, something like this should work:
let scannedTools = [
{barcode: "ABC", createdAt: "today"},
{barcode: "XYZ", createdAt: "123"}
];
function isAlreadyScanned(tool) {
return scannedTools.filter(t => t.barcode == tool.barcode ).length > 0
}
console.log(isAlreadyScanned({barcode: "ABC"}));
console.log(isAlreadyScanned({barcode: "ETRASDASD"}));
console.log(isAlreadyScanned({barcode: "XYZ"}));

What does these ES6 syntaxes really change?

Trying to learn some functional javascript and es6 concepts.
I have an array
var _ = require('underscore');
var raw =[
{
key :"name",value:"henry"
},
{
key :"age",value:"old"
},
{
key :"food",value:"matooke"
},
{
key :"kids",value:"Acacia"
},
{
key :"garbageA",value:"kasailoA"
},
{
key :"garbageB",value:"kasasiroB"
},
]
I am trying to filter out data with garbage keys . I have two codes that return different results and I wonder why they do not return the same results.
When i write
const endShape = _(raw)
.filter(key =>!/garbage/.test(key));
console.log(endShape);
in my console it prints.
[ { key: 'name', value: 'henry' },
{ key: 'age', value: 'old' },
{ key: 'food', value: 'matooke' },
{ key: 'kids', value: 'Acacia' },
{ key: 'garbageA', value: 'kasailoA' },
{ key: 'garbageB', value: 'kasasiroB' } ]
showing that my filter dint work.
When i write
const endShape = _(raw)
.filter({key} =>!/garbage/.test(key));
console.log(endShape);
It brings a syntax error.
But when i write
const endShape = _(raw)
.filter(({key}) =>!/garbage/.test(key));
console.log(endShape);
my filter works well and it prints
[ { key: 'name', value: 'henry' },
{ key: 'age', value: 'old' },
{ key: 'food', value: 'matooke' },
{ key: 'kids', value: 'Acacia' } ]
Why is it this way ? yet i know from phat arrow syntax that its okay to write
var x = y=>y+1;
and also
var x =(y)=>y+1
Actually the first and the second key for your filter is quite different.
On the first run when you do:
const endShape = _(raw)
.filter(key =>!/garbage/.test(key));
You are passing an object from your raw array, and your check is being evaluated like:
!/garbage/.test({ key: 'name', value: 'henry' })
Which will always be evaluated to false, and then you negate it so every condition will be true, thus your filter let every entry pass.
On the second run you do:
const endShape = _(raw)
.filter(({key}) =>!/garbage/.test(key));
Where you're destructuring key from your object, and thus the test makes sense, and your filter works fine!
Hope it helps!

set option value in dropdown

I am attempting to set an option in a dropdown/select. I have done this before, but for some reason I am getting an error and I am not sure why.
Code
var _loc = {
ALL_BUYS: [{ Text: "All Buys", Value: "AAA"}],
NETWORK_BREAK: [{ Text: "Network Break", Value: "NTN"}],
SYNDICATED_BREAK: [{ Text: "Syndicated Break", Value: "STA"}],
LOCAL_BREAK: [{ Text: "Local Break", Value: "LTA"}],
NATIONAL_LOCAL: [{ Text: "National/Local", Value: "LTN"}],
LOCAL_LOCAL: [{ Text: "Local/Local", Value: "LTL"}]//,
};
lstOptions = $("<select></select>");
$.each(_loc, function (i, item)
{
$("<option></option>")
.appendTo(lstOptions)
.html(item.Text)
.val(item.Value) // receive error: Object has no method 'val'
});
You're not grabbing the values from the object correctly.
The format is like so:
{key1:[{0, 1}], key2:[{0, 1}], key3:[{0, 1}]}
When you use $.each, it selects each one in this state:
[{0, 1}]
On the first iteration, it would select the value associated with key1, on the second, key2, etc.
Since you have arrays nested in each key's value, you need to specify that it locate the first array in the matched value:
var _loc = {
ALL_BUYS: [{ Text: "All Buys", Value: "AAA"}],
NETWORK_BREAK: [{ Text: "Network Break", Value: "NTN"}],
SYNDICATED_BREAK: [{ Text: "Syndicated Break", Value: "STA"}],
LOCAL_BREAK: [{ Text: "Local Break", Value: "LTA"}],
NATIONAL_LOCAL: [{ Text: "National/Local", Value: "LTN"}],
LOCAL_LOCAL: [{ Text: "Local/Local", Value: "LTL"}]
};
lstOptions = $("select");
$.each(_loc, function(i, item){
$("<option></option>")
.appendTo(lstOptions)
.html(item[0].Text)
.attr("value", item[0].Value);
});​
Demo.
Note the item[0]. What this does is select the array with the index 0 in the value that it grabbed. Since there is only one, that single array's index is 0, so it's selecting that specific one. Then you find and set its text and value.
Also note that I changed val() to attr(), because option elements don't support val() (you could, however, use it on a select element to set the option whose value is equal to the one specified in this function to make it selected).
TIP: You could also get rid of the literal array indicators around each nested object and use the original method. Demo.
<option> elements do not support val(). I think you want to use attr()
.attr("value", item.Value)
.val() is used to get the value of form elements. It is not a short-cut to setting the value attribute of an element. To do this, you can use:
.attr("value", item.Value)
Figured it out. I want my items in the loop to be in the following format
Item: "All Buys"
Value: "AAA"
Instead they were in this format
[0]Option
Item: "All Buys"
Value: "AAA"
If I change my loop to this it works
$.each(_loc, function (i, item)
{
$("<option></option>")
.appendTo(lstOptions)
.html(item[0].Text)
.val(item[0].Value);
});

Categories

Resources