How to create copy of an Array? [duplicate] - javascript

This question already has answers here:
Copy array by value
(39 answers)
Closed 9 years ago.
I have this code:
const settings = {
notes: [new musicnote(480,400,"wav/1.wav","cyan",true)],
emiters: [new emiter(300,240), new emiter(340,240)]
}
var notes = [];
var emiters = [];
var LoadLevel = function (level) {
if(settings[level] !== undefined){
currentLevel = level;
notes = settings[level].notes;
emiters = settings[level].emiters;
}
}
And when I change emiters array in game (delete or add some) it does the same to the settings.emiter array. So my question is - how to pass a new array instead of a reference to array in settings object?

You can do that with Array.slice:
var original = [];
var copy = original.slice();
// to test:
copy.push("foo");
alert(original.length); // 0

Related

How to push data without hardcoding the name [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 months ago.
I want to build an JSON with name and value like name:"john".
This is my code:
var allFields = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length;i++){
name = inputs[i].name;
item = inputs[i].value;
allFields.push({name: item});
}
var alleFelder = JSON.stringify(allFields);
alert(alleFelder);
My problem is that "name" gets hardcorded into the JSON.
So instead of...:
name:"john",
lastname:"brooks",
birthdate:"1.1.1999"
...im getting:
name:"john",
name:"brooks",
name:"1.1.1999"
You can use this simple function to add new keys with values to your object
const myObj = {}
function addKeyVal(obj, k, v){
obj[k] = v;
}
const keys = ["name", "bday"];
const values = ["Jhon", "1-1-2020"];
for(let i = 0; i < keys.length; i++)addKeyVal(myObj, keys[i], values[i])
console.log(myObj)

Javascript multidimensional array key - val [duplicate]

This question already has answers here:
Zip arrays in JavaScript?
(5 answers)
Closed 5 years ago.
In my javascript function i have two single array like this:
var row = ["var1","var2","var3"];
var col = ["res1","res2","res3"];
i would create a multidimensional array like:
[["var1","res1"],["var2","res2"],["var3","res3"]]
i tried:
new Array(m).fill(new Array(n).fill(0));
or solution like:
var dict = [[]];
for (i = 0; i < descendents.length; i++) {
e = descendents[i];
dict[i] = dict[i][e.id]
dict[i] = dict[i][e.value]
}
but the result is not correct for me. i don't know how achieve this
Thanks in advance
Use Array#map to generate a new array based on existing.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
// iterate and generate new array based on row array element
// and fetch element from col using the same index
var res = row.map((v, i) => [v, col[i]]);
console.log(res)
Or with Array.from with a map function.
var row = ["var1", "var2", "var3"];
var col = ["res1", "res2", "res3"];
var res = Array.from({ length: row.length }, (_, i) => [row[i], col[i]]);
console.log(res)

Copy an array without linking to it [duplicate]

This question already has answers here:
Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop
(25 answers)
Closed 6 years ago.
var ProtVar = function(arr){
this.gr1 = [];
this.gr2 = [];
this.arr = arr;
return this;
}
ProtVar.prototype.setArrs = function(){
this.gr1 = this.arr;
this.gr2 = this.arr;
return this;
}
ProtVar.prototype.shiftGr1 = function(){
this.gr1.shift();
return this;
}
ProtVar.prototype.showData = function(){
console.log("gr1 = ", this.gr1.length, this.gr1);
console.log("gr2 = ", this.gr2.length, this.gr2);
console.log("arr = ", this.arr.length, this.arr);
return this;
}
var protVar = new ProtVar([1,2,3,4]).setArrs().shiftGr1().showData();
How should I copy the array without linking to the same array?
I figured out how to do this with slice(0); see below.
ProtVar.prototype.setArrs = function(){
this.gr1 = this.arr.slice(0);
this.gr2 = this.arr.slice(0);
return this;
}
Is this the right way to do it?
There are at least 4 (!) principal ways to clone an array:
loop
constructor
slice / splice
concat
Please see this answer

Creating arrays in javascript dynamically [duplicate]

This question already has answers here:
Alter and Assign Object Without Side Effects
(7 answers)
Closed 9 years ago.
I'm new in Phonegap app development.
I want to create an array of this type.
var myColumnDefs = [
{id:"id1", name:"name1"},
{id:"id2", name:"name2"},.... ] ;
Please help me how I can do this using javascript.
Because I have to insert data in this coming from webservices.
try this code..
var dataArray = [];
var length = yourjsonAray.length;
for (var i = 0; i < length; i++) {
var obj = {
id: yourjsonAray.keyId[i].id,
name: yourjsonAray.keyName[i].name
};
dataArray.push(obj);
}
Define an array (main array)-
var myColumnDefs = new Array();
and an object
var myObj = new Object();
then in your for loop, simply -
myObj.id = "ID1";
myObj.name = "Name1";
myColumnDefs.push(myObj);
OR, (better way)
function myObj(id, name)
{
this.name = name;
this.id = id;
}
myColumnDefs = new array();
myColumnDefs.push(new myObj("ID1", "Name 1"));
and so on ..

How to in JavaScript or ExtJS: obj['a.b.c'] = 123 => obj.a.b.c = 123? [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 9 years ago.
I need to convert an object with cannonical properties into object with nested properties, splited by '.'
Example:
From:
obj['a.b.c'] = 123;
to:
obj.a.b.c = 123;
Any elegant solutions?
Or maybe there is a solution in ExtJS to make form.getValues() to return an array of fields grouped by names like fieldname[1] or fieldname.1?
Have a look at the private method in ClassManager "createNamespaces". It's essentially what you need to do, except root shouldn't default to global, it should default to your object:
function setValue(o, key, value) {
var root = o,
parts = key.split('.'),
ln = parts.length,
part, i;
for (i = 0; i < ln; i++) {
part = parts[i];
if (typeof part != 'string') {
root = part;
} else {
if (!root[part]) {
root[part] = (i === ln - 1) ? value : {};
}
root = root[part];
}
}
}
var o = {};
setValue(o, 'a.b.c', 123);
console.log(o.a.b.c);

Categories