Set Objects Key Value - javascript

I am using jQuery to iterate through a Javascript object and I would like to set the key value of one or more of the objects keys from within the loop.
var children = $(clone).children();
$.each(obj, function(k, v) {
if(v == undefined) {
//Loop through data array and match.
for(var i=0; i<children.length; i++) {
var dataId = children[i].id.split('.');
if(k == dataId[1]) {
obj.k = children[i].value; //This is the value I want to set on the key.
}
}
}
});
The children variable is an array of children (input and select objects) within a div. The loop is passed an object and runs through all the keys in the object. In this case the object is a phone numbers and its keys are similar to number, type, primary etc. but that doesn't matter much. If a key on the object is undefined I want to populate that key with a value from its matching child object.
Everything is working perfectly except I cannot figure out how to set the key with a new value.

use
obj[k] = children[i].value;
note that foo['bar'] is equivalent to foo.bar

Related

javascript - search for string in array of objects and return array

I would like to write a function that will search the fields of objects in an array for a specific string, adding this object to a new array if the string is found in any of the object's fields. I've gotten my function to work, but was having the issue of the new list containing multiple copies of the objects which contain multiple copies of the string being searched for. I know this is because I've looped it so that each field it finds the string in, it will add the object once more to the new array. However, I wasn't sure of what alternative way I could go about writing the function to add the object only once, regardless of how many of its fields have matched with the string being searched for. This is my function:
function search (keyword, array){
var newArray = [];
for(let i = 0; i < array.length; i++) {
for (key in array[i]) {
if(array[i][key].includes(keyword)){
newArray.push(array[i]);
}
}
}
return newArray;
}
An example of where the output is problematic is if I do:
console.log(search('yes', myArray))
And if myArray contains an object in which 'yes' appears in 3 different fields, it will add this object to newArray 3 times.
Improved version of Danny Buonocore code.
No accidental global variables.
Uses forEach to iterate over the array.
Uses for...of and Object.values() to iterate over the values of the object (using for..in iterates over all non-Symbol, enumerable properties of an object itself and those the object inherits from its constructor's prototype and are cause for many bugs)
"short circuit" the test for adding an object: if a value has matched, there is no need to check the other values. This alone would probably solved your problem, but using a set will prevent duplicates if you have the same object multiple times in your array.
function search (keyword, array){
var result = new Set();
array.forEach( object => {
for (const value of Object.values(object)) {
if ( value.includes(keyword) ) {
result.add(object);
continue; // Don't need to check more on this item.
}
}
});
return Array.from(result);
}
console.log(search("yes", [
{ key1 :"yes", key2:"yes" },
{ key1 :"no", key2:"no" }
]));
You could use a Set, this will prevent duplicates.
function search (keyword, array){
var result = new Set();
for(let i = 0; i < array.length; i++) {
for (key in array[i]) {
if(array[i][key].includes(keyword)){
result.add(array[i]);
}
}
}
return Array.from(result);
}

Change key's value in array of objects with javascript?

I am building a page that allows customers to change information, which is then passed to the admin team to verify before accepting. I am trying to keep the form dynamic in only passing information that was changed by the customer. I'm using the function below to create an array of objects:
$('input, textarea, select').change(function(){
var key = $(this).attr('name');
var obj = {};
obj[key] = $(this).val();
myArray.push(obj);
});
Which is working correctly, however today I noticed that when changing the field multiple times it created multiple objects with the same name.
My question is how can I find the key which is dynamic and change the value if it exists in the array?
I tried using:
$.each(myArray, function( key, value ) {
console.log(key, value);
});
But this outputs the index and then the complete object, I need to find the key of the object and then change the value if it already exists.
The variable myArray is a array not a object, so the key is just the index of the object in the array.
To check if the object with the specific key exists,
function getObjWithKey(myArray, key){
var retVal;
$.each(myArray, function(index, obj) {
if(key != undefined && obj[key]){
retVal = obj;
return false;
}
});
return retVal;
}

Assigning a javascript object with and object inside an array

I am just curious about this.
Let's say I have an array of objects and I create 1 object, lets name the array of objects items and the object item.
I want to get a particular item in my array of items by using the following code:
//gets an item base on ID
function get_item(td){
var item = undefined;
$.each(items, function(i, val) {
if(val.item_id == td){
item = val;
}
});
return item;
}
The get_item() basically gets an object matched with the supplied id.
So my question is this. What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Thank you very much!
What if I changed the properties of item will it also changed the properties of an object associated with it within the array?
Yes.
Objects are not copied. Instead, references to the objects are passed around. Simplest example:
var a = [];
var b = a;
b.push(1);
console.log(a); // logs [1]
Many object-oriented programming languages work like this.
The value of the object inside the array will also change because it's a reference. If you want more information I highly recommend reading Objects and Prototypes.
If you don't want it to change then you should use something like lodash's _.clone() function.
Also you could use filter to get the object:
function get_item(td){
return items.filter(function(item) {
return item.id === td;
})[0];
}
You can update you function to:
var data= array();
function get_item(propertyValue, propertyName){
var retval;
for(var i = 0; i < data.length; i++){
if(data[i][propertyName]==propertyValue){
retval = data[i];
break;
}
}
return retval;
}
Use it
var item1 = get_item(1,"id");
var item2 = get_item("john","name");

Explanation for in loop javascript

I'm having trouble understanding the way this for in loop works.
function createSimpleNode(name, options, text) {
var node = document.createElement(name);
for (var o in options) {
node.setAttribute(o, options[o]);
}
if (text) {
node.innerHTML = text;
}
return node;
}
The For in loop gives a way to iterate over an object or array with each value and key.
It can be applied over an object or Array.
For an Object
For an object it gives each key in the object as the ITER variable. Using this variable you can get the corresponding value from object.
var options = {a:1,b:2};
for (var key in options) {
console.log(o,options[key]);
}
Will Iterate over the options object and print each key and it's value.
a 1 //first key is a and options["a"] is 1
b 2 //first key is a and options["b"] is 2
For an Array
For an array it gives each index in the array as the ITER variable. Using this variable you can get the corresponding element from array.
var options = ["a","b"];
for (var index in options) {
console.log(index,options[index]);
}
Will Iterate over the options array and print each index and element on given index. Output will be:-
0 a //first index is a and options[0] is a
1 b //second index is a and options[1] is b
This is a for..in loop. it iterates over the properties of an object (options, in this case), and allows you access the said property in each iteration using the [] operator.
In your example, you iterate over options properties, and set them all as attributes of node.

javascript delete from array based on another array with same object and values

I have an array of objects (all the same object type). I have another array of the same object type in which I want to use to tell me which objects to delete from the first array. Is there an easy way to do this besides looping through all properties and comparing them to find the elements in the first array that 100% match the elements in the second array and then deleting from the first array?
I'm basically doing a jQuery.grep() on an array of objects and the resulting array from this grep I want to delete from the array I passed into it.
Instead of using jQuery.grep(), to obtain a new array, replace it with jQuery.map(), returning the same object if it must be kept, or null if you want to remove it.
If for instance your code is
var toBeDeleted = $.grep(array, function(val) {
return condition(val);
});
Change it to
array = $.map( array, function(val) {
if(condition(val))
return null;
return val;
});
If all it is is an array of values that need to be deleted from another array then looping through the arrays is really quite easy.
function deleteMatchingValues( target, toBeDeleted, oneMatch ) {
var i = target.length, j = toBeDeleted.length;
while( i-- ) {
while( j--) {
if( target[i] === toBeDeleted[j] ) {
target.splice(i,1);
if( oneMatch ) { break; }
}
}
j = toBeDeleted.length;
}
}
The above function includes a parameter for when you know there is only single instances of the value in the array.

Categories