How to overwrite JavaScript object values using Object() - javascript

I am still somewhat new to JavaScript, Node, etc. and come from a Groovy background (which has extremely similar syntax to JavaScript). In Groovy, I can easily do something like this:
def myMap1 = {};
def myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
myMap1.each() { key, value =>
myMap2[key] = value;
}
This would iterate through the existing map (myMap1) and copy the values for each key to the new map (myMap2), with the same key names. Easy as pie. However, JS has a concept of the prototype, which has been driving me crazy because you have to use hasOwnProperty, the index of the item sort of thing, etc and it results in a lot of code for something that's supposed to be really simple.
Looking at the MDN docs for Object(), it looks like JS has implemented something that allows a developer to access key/value pairs without having to deal with prototyping and all of that stuff, and you can just access the data in the object, and not properties of the object. I now have this:
var existingData = {"foo":"thing","bar":"otherThing","baz":"whatever"};
var update = {"foo":"newStuff","bar":"thisChanged","baz":"arghh"};
for (const [ key, value ] of Object.entries(update)) {
console.log("Old value is " + existingData[key]);
existingData[key] = value;
console.log("Setting " + existingData[key] + " to " + value);
}
I would think this would work, but I get this in the console instead:
Old value is undefined
Setting thing to thing
Old value is undefined
Setting otherThing to otherThing
Old value is undefined
Setting whatever to whatever
It looks like existingData[key] does not reference the key in the key/value pair, but instead the value or something? How do I tell it, "for this key name in this second object, set this value?" I've been searching forever on Google and everything is either doing it the old way (with indexes) or is overly complicated for no particular reason. Any help would be greatly appreciated.

for (let key in map1) {
map2[key] = map1[key];
}
BTW why you dont use Object.assign(); ? (notice: it returns a new object)
let update = { "key1": "value1", "key2": "value2" };
let map2 = Object.assign({}, map1, update);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Simply use Object.assign(map2, map1) to update map2 (copy key/value of map1 to map2)
Or you can use,
map2 = {...map2, ...map1} to build a new object and replace the map2 completely
To have a deep copy, instead of only first level you can use JSON.parse(JSON.stringify(map2)) instead of map2. If you think, its a large object and that impact performance, go for a nested implementation of copy recursively! ;-)

You could just do this - looping through an array of the keys:
let myMap1 = {};
let myMap2 = {};
myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";
// create an array of the keys in the object myMap1
let myMap1_keys = Object.keys(myMap1);
// loop through the array of object keys
for (let i = 0; i < myMap1_keys.length; i++) {
myMap2[myMap1_keys[i]] = myMap1[myMap1_keys[i]];
}
I would advise not using a for..in loop i.e. as used in one of the other answers as these are slower than a native for loop (as used above). You can see some details regarding performance here: Comparing JavaScript loops performance (for, do while, for in)
If you are just interested in literally duplicating the object you can do that like so:
let myMap2 = JSON.parse(JSON.stringify(myMap1));
Anouther answer suggested using Object.assign() and anouther suggested using ES6 spread operators but these will 'shallow' copy the object which means the objects are using references to the original object and will only copy the top level of the object - the method above deep copies the object which I usually find is what is required for most use cases and will copy every level of the object.

You can iterate over keys. check is this helpful to you
var m1 = {};
let m2 = {};
m1["key1"] = "abc";
m1["key2"] = "def";
m1["key3"] = "ghi";
var m1_change_key = Object.keys(m1);
for (var i = 0; i < m1_change_key.length; i++) {
m2[m1_change_key[i]] = m1[m1_change_key[i]];
alert(m2[m1_change_key[i]])
}

Related

what does mean by this line of code in JS obj[{key:"value"}] = "value";

let obj = {};
obj[{key:"instagram"}] = "Akrixa";
obj[{key:"facebook"}] = "Coding with Akrixa";
console.log(obj[{key: "instagram"}]);
This is a problem in which I'm confused with 2nd and 3rd line of code, what does by those lines?
obj[{key:"instagram"}] = "Akrixa" is equivalent to
obj[({key:"instagram"}).toString()] = "Akrixa" since objects are keyed by strings. So it's equivalent to
obj["[object Object]"] = "Akrixa"
I think because obj[{key:"instagram"}] and obj[{key:"facebook"}] are the same object. When assign value for it, it has the same value. More detail: How to create dictionary and add key–value pairs dynamically?. I wish its help you
The second line obj[{key:"instagram"}] = "Akrixa"; creates a key within your obj [{key:"instagram}] (which is an object inside an array) and then sets the value of that key to Akrixa, and the third line does the same but with a different key and value.
It might be better to use obj["instagram"] = "Akrixa" and obj["facebook"] = "Coding with Akrixa" as to avoid excessive complication, and you can then refer to it with obj["instagram"] etc.
let obj = {};
obj["instagram"] = "Akrixa";
obj["facebook"] = "Coding with Akrixa";
console.log(obj["instagram"]);

Strange behavior in jQuery loop with arrays

I am having an issue with the following code:
var samount = [{value:100, name:'USD'},
{value:200, name:'USD'},
{value:100, name:'USD'}];
var object1 = new Array;
objects1 = samount;
var categories1 = new Array();
var groupedObjects1 = [];
var output1 = '';
var i = 0;
console.log(samount);
_.each(objects1,function(obj){
var existingObj;
if($.inArray(obj.currency,categories1) >= 0) {
existingObj = _.find(objects1,function(o){return o.currency === obj.currency;});
existingObj.value += obj.value;
} else {
groupedObjects1[i] = obj;
categories1[i] = obj.currency;
i++;
}
});
console.log(samount);
console.log(groupedObjects1);
The problem is that I do not want that samount variable to change after looping, so I have done this:
var object1 = new Array;
objects1 = samount;
The goal of this script is to sum up all values from the same currencies, but still to not mess with the initial array.
But it still changes the initial Array. Could anyone help me with this error?
Copy the array with slice
var objects1 = samount.slice(0);
Arrays and object are passed by "reference" (not really, but doesn't matter here), so when assigning an array to a new variable, all you get is a reference to the same array, not a new array.
You need to deep copy the initial array instead of affecting it.
var samount = [{value:100, name:'USD'},
{value:200, name:'USD'},
{value:100, name:'USD'}];
var object1 = $.extend(true, [], samount);
You were doing an affectation (i.e. 2 variables pointing to the same object) where you needed a copy (2 variables pointing to 2 different objects)
The problem is you're not creating a copy with
objects1 = samount
In most OO languages, you can only copy primitive types so int, strings characters etc, but not objects.
This is somewhat similar in javascript in the sense that {} is an object, same as Array or [].
So if you want to copy an object you'd have to iterate over every element of that object till you find an primitive type. This can be tedious and quite hard even (http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/) this is called a deep copy.
But in this case a shallow copy (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) is enough
var objects1 = samount.slice(0);

JavaScript Two dimensional Array

I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;

Jquery fill object like array

This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).

Add dynamic key, value pairs to JavaScript array or hash table

I'm trying to add a key value pair to an existing javascript associative array. The key needs to be a variable. This is for JSON encoding. I realize there are many plugins and frameworks for this, but I want a simple answer.
ary.push({name: val});
where ary is a new array, name is a variable containing the key, val is the value of this entry.
I'm doing this in a jQuery loop that iterates through form fields.
In ES6...
In ES6, you can use a destructuring assignment;
ary.push({[name]: val});
However, given this is ES6 syntax, the usual caveats apply; this will not work in some browsers (noticably, IE and Edge 13)... although Babel will transpile this for you.
Without ES6 (legacy browser support)...
You need to define an object and use square bracket notation to set the property;
var obj = {};
obj[name] = val;
ary.push(obj);
If you get the urge to read into it more, see this article on the differences between square bracket and dot notation.
var ary = [];
function pushToAry(name, val) {
var obj = {};
obj[name] = val;
ary.push(obj);
}
pushToAry("myName", "myVal");
Having just fully read your question though, all you need is the following
$(your collection of form els).serializeArray();
Good old jQuery
An "associative array" is really just an object. You don't use push, you just assign properties to the object:
ary[name] = val;
The following code will help you
ary.push( {[name]: val} );
See below example
let allData = [{name: "Cat", type: "Animal"}]
let finalData: any = [];
for (let i = 0; i < allData.length; i++)
{
let obj = allData[i];
for (let KEY in obj)
{
//Pushing data to other array as object
this.finalData.push({ [KEY] : obj[KEY] });
}
}
const tStyles = [];
for (const i of iStyles) {
const temp = {};
temp[`${style}`] = `../dist/css/uikit.${wFile}.${style}.css`;
tStyles.push(temp);
}
json : {"black-beige":"../dist/css/uikit.or.black-beige.css"}

Categories