Javascript merge two object and set to global object each time [duplicate] - javascript

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 years ago.
I need to merge two javascript object and set it to my global object. I'm using "Object.assign" method but it doesn't work.It works right when it called first time. But I need to merge each time my new object to the global object. But it doesnt work more first time ,it makes my global just same as last object.Do you know any other way to make it ? Thanks in advance :/
Javscript codes :
//global object
Admin.bufferCreateJSON={};
Admin.createBufferJSON=function(){
var B_name=$("#B_name").val();
var B_description=$("#B_description").val();
var B_bufferType=$("#bufferTypeSelect").val();
var bufferData={};
var common = {'name': B_name,'description': B_description};
bufferData=Object.assign(bufferData, common);
var bufferType={ 'bufferType[id]': B_bufferType}
//following codes works right
bufferData=Object.assign(bufferData, bufferType);
//Admin.bufferCreateJSON is my global variable
// But when I want to merge it to my global variable it doesnt work
Admin.bufferCreateJSON=Object.assign(Admin.bufferCreateJSON, bufferData);
//shows me just last one
console.log(Admin.bufferCreateJSON);
}

let mergedObj = Object.assign({}, obj1, obj2, obj3); is the best way.
Snippet of your case:
var Admin = {
bufferCreateJSON: {
a: 123,
b: 321,
}
}
Admin.createBufferJSON=function(tmp){
var B_name = 'B_name' + tmp; //$("#B_name").val();
var B_description = 'B_description' + tmp; //$("#B_description").val();
var B_bufferType = 'B_bufferType' + tmp; //$("#bufferTypeSelect").val();
var common = {'name': B_name,'description': B_description};
var bufferData=Object.assign({}, common);
var bufferType={ 'bufferType[id]': B_bufferType}
bufferData=Object.assign({}, bufferData, bufferType);
Admin.bufferCreateJSON=Object.assign({}, Admin.bufferCreateJSON, bufferData);
console.log(Admin.bufferCreateJSON);
}
Admin.createBufferJSON(1)
Admin.createBufferJSON(2)
Console output:
Object {a: 123, b: 321, name: "B_name1", description: "B_description1", bufferType[id]: "B_bufferType1"}
Object {a: 123, b: 321, name: "B_name2", description: "B_description2", bufferType[id]: "B_bufferType2"}
Object contain a and b from globals object and name, description, bufferType[id] are replaced as expected.
if you want only to add new properties without replacement of exists properties you can change assign order:
Admin.bufferCreateJSON=Object.assign({}, bufferData, Admin.bufferCreateJSON);

Related

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Angular / Javascript search array for object key

For the purpose of example lets have the following object:
var myobj = {id: 1, text: 'hello world', user_id: 5}
Now lets say we have an array:
var objectContainer = []
And we fill this objectContainer with x number of myobj
Now we wish to find the myobj that has the id value set to 30
You could use a loop but in worst case you would have to loop through the whole array before finding your value.
So my question is does JaVaScript have a function for these situations or does AngularJsprovide additional helpers to solve this?
You have a lot of different solutions :
Javascript FIND : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example :
var myobject = objectContainer.find(function(value){ return value.id === 1; });
Angular filter : https://docs.angularjs.org/api/ng/filter/filter
If your ids are unique you could also use a map instead of an array :
Exemple :
var myobj = {id: 1, text: 'hello world', user_id: 5};
var objectContainer = {};
objectContainer[myobj.id] = myobj;
etc
Your value of 'x' is the array indexer. So objectContainer[29] should point to the myobj in the 30th position.
Also you can use my solution of finding objects in an array.
But still it will loop over all elements of an array.

Can variable in javascript generate variables? [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
Let's think about this:
var list = [a1:"123",b2:"234",c3:"345"];
This list obj can create variables by key name like this?
var a1 = list[0];
var b2 = list[1];
var c3 = list[2];
When you use [] notation, you can only create arrays with numeric indexes. To have named properties, you must use {} object notation:
var list = { a1: "123", b2: "234", c3: "345" };
You can then access them as list.a1, list.b2, and list.c3.
The question is not clear. What you show in the example is valid. But you could also create variable names like you suggest like
for( var key in list ) {
window[key] = list[key];
}
This way you will end up having a1, b2 and c3 variables with the desired value, however, these will be globals.
First of all you have a mistake, you are trying to merge hash array and regular array. You should either announce an array like this:
var list = ['123', '234', '345']
and then
var a1 = list[0]
and so on, or announce it like hash array and it will look like this
var list = {'a':'123','b':'234','c':'345'}
var a1 = list.a

How to assign a Javascript array through it's indexes [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically creating keys in javascript associative array
usually we initialize an array like this:
var ar = ['Hello', 'World'];
And for access to it's values we do:
alert(ar[0]); // Hello
But I want a custom index to assign, ex:
var ar = ['first' => 'Hello', 'second' => 'World'];
and then
alert(ar['first']);
But I can't find how, is there something like this that I could do for assign?
Thank's!
You could use Object instead of Array, you can specify named properties for object
var ar = {
first: 'hello',
second: 'world'
};
alert(ar['first']);
Also you can just assign properties with string keys to your array, this will also work:
var ar = [];
ar['first'] = 'first';
alert(ar['first']);
You need to use an Object.
var obj = {'first': 'hello', 'second': 'world'};
alert(obj.first);
Objects in JavaScript are just property bags (hashtables).
You can:
var ar = {};
ar["name"] = "Dave";
ar["salary"] = "Millions";
alert(ar.name); //Dave
alert(ar["salary"]); //millions
JavaScript allows you to be pretty flexible in how you create these objects.
JavaScript doesn't have associative arrays as such, but object literals:
var obj = {foo:'bar'};
obj.something = 'else';
//or:
obj['foo'] = 'BAR';
JS won't make a fuss if you create named indexes on an array (because the Array object traces back to the Object prototype) but you'll loose all use of Array features (methods like sort, or the magic length property, to name just a few)
just use
var h = new Object(); // or just {}
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
// show the values stored
for (var k in h) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}
You can do this:
var ar = {
'first' :'Hello',
'second' : 'World'
};
As you can see, this is the way you initialize objects in Javascript. Javascript blurs the lines between associative arrays and objects.
You can then access this with:
ar['first']
Or even:
ar.first
Also, you could leave out the quotes in the key initialization, like so:
var ar = {
first :'Hello',
second : 'World'
};

Learning to programming JavaScript, but I'm stuck

Yesterday I started learning JavaScript. I am using the system Codecademy, but I'm stuck. When I say "stuck", I mean I have assignment with which I cannot see what is wrong.
The assignment is:
Create an array, myArray. Its first element should be a number, its second should be a boolean, its third should be a string, and its fourth should be...an object! You can add as many elements of any type as you like after these first four.
This is the code I made:
var myObj = {
name: 'Hansen'
};
var myArray = [12,true, "Steen" ,myObj.name];
The error:
Oops, try again.
Is the fourth element of myArray an object?
Hope you can help me.
The problem with your fourth element is you are passing a string because myObj.name is defined as Hansen. Pass the object instead:
var myArray = [12,true, "Steen" ,myObj];
I don't know that site, but you can do:
var myArray = [
12,
true,
"Steen",
{name: 'Hansen'}
];
What you are passing to the array is the value of the name property of your object instead of the object itself.
Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers.
As your learning here are a few ways to do exactly the same thing as your accomplishing here.
Your way corrected:
var myObj = {
name: 'Hansen'
};
var myArray = [12, true, "Steen", myObj];
Other ways:
// Method 1
var myArray = [12, true, "Steen", {name: 'Hansen'}];
// Method 2
var myObj = new Object();
myObj.name = "Hansen";
var myArray = new Array(12, true, "Steen", myObj);
// Method 3
var myObj = {};
myObj['name'] = 'Hansen'
var myArray = [
12, true, 'Steen', myObj
]
Each method shows a few different ways to do the same thing, you can mix and match the equivalent parts of code to get the same job done. It's basically inter changing between the normal JavaScript syntax and object literal syntax.

Categories

Resources