Change key's value in array of objects with javascript? - 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;
}

Related

How to add Key on existing array javascript

im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array.
i have an object that i wanted to be converted on array javascript.
here is my code on how to convert my object to array.
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) { return obj[key]; });
var site_key = $.map( obj, function( value, key ) {
return key;
});
the site_value has the value of my objects.
the site_key has the key.
i want to add my site_key to the site_value array as a Key.
example data:
site_value:
0:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
site_key:
Array[49]
0:"AGB"
1:"BAK"
2:"BAN"
3:"BAR"
i want my array to be
AGB:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
Update:
Here is my object.
Array[1]0:
Object
AGB: Array[4]
BAK: Array[4]
BAN: Array[4]
etc.
You have almost done it and I have modified it a bit below to return it as array object,
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) {
var output = {};
output[key] = obj[key];
return output;
});
I might be misunderstanding the question, sorry if I am. I think you would like to use a key "AGB" instead of an integer for an array index. In this case, you would probably be better served to use an object instead of an array. Maybe something like this
var myObject = {
AGB: Array[4],
AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};
Then you could access AGB by key and your additional arrays by index

Checking for the last element in a JQuery each function

I have an object that I am iterating through using JQuery's each function. However, the solution posted in this stack overflow post doesn't work when I tried using the length property. I got undefined in the console when I tried getting a length property value, which I believe this is because I am iterating through an object and not an array.
My code:
$.each(attributes, function(key, value) {
attrKey = key;
attrVal = value;
console.log(attributes.length); //returns undefined
//do something if it is the last element
});
Try plain Javascript instead:
for (var key in attributes) {
var value = attributes[key];
// process key,value...
}
Edit:
If you're trying to get the last key/value in an object, you can't. Javascript objects are unordered, meaning that they do not keep track of when additional key/value assignments are made. If order is important, I would recommend changing attributes be an array of objects, where each object is a single key/value, or use a 3rd party library, like this - https://github.com/trentrichardson/Ordering.
If you'd like to get the number of keys in attributes, use Object.keys:
Object.keys(attributes).length
Try
var index = 1;
$.each(attributes, function(key, value) {
if(Object.keys(attributes).length == index)
{
// Do something
}
index++;
});
per #PaulFrench's comment:
length = Object.keys(attributes).length;
if(n < length) {
//do something
}

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");

Get Key From Value in Key-Value Pair

I have something like this:
var input = [];
var result = {};
input.push({
key: 1,
value: Value
});
result[input[0].key] = input[0].value;
If I want to get the value from key i call result[key], but what if I want to get the Key from a certain value? Any ideas?
You could create an inverse mapping of values → keys; however, there is no guarantee that the values will be unique (whereas the keys must be), so you could map values → array of keys.
function inverseMap(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var val = obj[key];
if (!memo[val]) { memo[val] = []; }
memo[val].push(key);
return memo;
}, {});
}
var a = {foo:'x', bar:'x', zip:'y'};
var b = inverseMap(a); // => {"x":["foo","bar"],"y":["zip"]}
[Update] If your values are definitely unique then you can simply do this:
function inverseMap(obj) {
return Object.keys(obj).reduce(function(memo, key) {
memo[obj[key]] = key;
return memo;
}, {});
}
inverseMap({a:1, b:2})); // => {"1":"a","2":"b"}
Of course, these solutions assume that the values are objects whose string representation makes sense (non-complex objects), since JavaScript objects can only use strings as keys.
A value might have several keys, so I'd recommend iterating over all the keys and adding those that have value into a list.
Do you plan to recurse for complex values?
You could use underscore.js's find method...
var key = _.find(result, function(val) {
return val === 'value';
}).key;
This will search your result for the value and return you the object, then you can grab the key off of it.
Underscore is one of my favorite tools for handling these kinds of things. There's lots of powerful methods in it.

Set Objects Key Value

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

Categories