Specifying a variable as an array destination in Javascript ( mutability? ) [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
I have 5 arrays in Javascript that I’ll fill and whichever array I fill will depend on the value of “x”. I am getting hopelessly confused regarding variable usage/mutability here. My code is below….
//Node arrays that hold the IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];
var nodesButtonToNode = {pn_btn_1:"nodeOne", pn_btn_2:"nodeTwo", pn_btn_3:"nodeThree", pn_btn_4:"nodeFour", pn_btn_5:"nodeFive"};
x = "pn_btn_1";
nodesButtonToNode.x.push("I am supposed to go into nodeOne")
In a nutshell if x = “pn_btn_1” that would then pull the value of the array that needs to be filled by specifying the key in nodesButtonToNode. In this case that array would be nodeOne. If x = “pn_btn_2” then the area that would need to be added to would be nodeTwo. As expected I am getting lots of undefined errors and I'm not sure where I'm going wrong.
Many TIA for any pointers

You should use an object with the array names as the keys, then you can access them via bracket obj[var] notation:
//Node arrays that hold the IDs of each node
const nodes = {
nodeOne: [],
nodeTwo: [],
nodeThree: [],
nodeFour: [],
nodeFive: []
};
var nodesButtonToNode = {
pn_btn_1: "nodeOne",
pn_btn_2: "nodeTwo",
pn_btn_3: "nodeThree",
pn_btn_4: "nodeFour",
pn_btn_5: "nodeFive"
};
x = "pn_btn_1";
nodes[nodesButtonToNode[x]].push("I am supposed to go into nodeOne");
console.log(nodes);

Your nodesButtonToNode should use the actual arrays rather than their names.
var nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
This will let you update the arrays directly.
Also, the value of x isn't in your mapping it should be pn_btn_1
//Node arrays that hold the IDs of each node
nodeOne = [];
nodeTwo = [];
nodeThree = [];
nodeFour = [];
nodeFive = [];
var nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
x = "pn_btn_1";
nodesButtonToNode[x].push("I am supposed to go into nodeOne");
console.log(JSON.stringify(nodeOne));

You have some errors in your syntax, check out example
const nodeOne = [];
const nodeTwo = [];
const nodeThree = [];
const nodeFour = [];
const nodeFive = [];
const nodesButtonToNode = {
pn_btn_1: nodeOne,
pn_btn_2: nodeTwo,
pn_btn_3: nodeThree,
pn_btn_4: nodeFour,
pn_btn_5: nodeFive
};
const x = "pn_btn_1";
nodesButtonToNode[x].push("I am supposed to go into nodeOne");
console.log(nodesButtonToNode);

Related

Make key value pair from two different array [duplicate]

This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]

What do the three dots "..." do in JavaScript [duplicate]

This question already has answers here:
Javascript Property with three dots (...)
(5 answers)
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I have gone through the following JavaScript code:
let num = [1,2,2,2,3,4,5];
console.log([... new Set(nums)]); //which prints [1,2,3,4,5]
I did not understand what this ... device (three dots) does in this example.
I think you need to read Iteration first;
let nums = [1,2,2,2,3,4,5];
let setFromArray = new Set(nums);
let arrayFromSet_spread = [...setFromArray];
console.log("spread", arrayFromSet_spread);
// here the spread will iterate over iteratable and return current value
//arrayFromSet can be written without spread like this
let arrayFromSet_forOf = [];
for ( let el of setFromArray ) {
arrayFromSet_forOf.push(el)
}
console.log("forOf",arrayFromSet_forOf);
// and the most naive way to iterate :)
let arrayFromSet_ManualIteration = [];
let setFromArrayIterator = setFromArray[Symbol.iterator]();
const firstElement = setFromArrayIterator.next();
const secondElement = setFromArrayIterator.next();
const thirdElement = setFromArrayIterator.next();
const fourthElement = setFromArrayIterator.next();
const fifthElement = setFromArrayIterator.next();
const sixthElement = setFromArrayIterator.next();
arrayFromSet_ManualIteration.push(firstElement);
arrayFromSet_ManualIteration.push(secondElement);
arrayFromSet_ManualIteration.push(thirdElement);
arrayFromSet_ManualIteration.push(fourthElement);
arrayFromSet_ManualIteration.push(fifthElement);
arrayFromSet_ManualIteration.push(sixthElement);
//you could just push values not the itaration object itself
//arrayFromSet_ManualIteration.push(firstElement.value);
//arrayFromSet_ManualIteration.push(secondElement.value);
//arrayFromSet_ManualIteration.push(thirdElement.value);
//arrayFromSet_ManualIteration.push(fourthElement.value);
//arrayFromSet_ManualIteration.push(fifthElement.value);
console.log('ManualIteration full objects',arrayFromSet_ManualIteration);

CasperJS array.push Making Variables Null

I have a custom data type that I am populating, I have verified that data populates correctly but when I try to push it to an array the result is both the array and the custom data type variable are null. Here is an example of what I am doing:
var values = [];
var temp = {};
temp['one'] = rows[i].cells[1].innerText.trim();
temp['two'] = rows[i].cells[2].innerText.trim();
temp['three'] = rows[i].cells[3].innerText.trim();
temp['four'] = rows[i].cells[4].innerText.trim();
values.push(temp);
When I output temp before values.push(temp); all expected values are present. When outputting either values or temp after values.push(temp); both are null.
Very confused, any help is appreciated.
Declare array and object like this..
var values = [];
var temp = {};
Example:
var values = [];
var temp = {};
temp['one'] = 'one';
temp['two'] = 'two';
temp['three'] = 'three';
temp['four'] = 'four';
values.push(temp);
console.log(values);
This was a dumb mistake on my part, nothing to do with the .push but want to answer for anyone else having the problem.
var values = [];
Was declared outside of any function, I thought I could do this and it would be global but that was a newbie mistake.

Javascript: how to dynamically create nested objects INCLUDING ARRAYS using object names given by an array

Very similar to this question:
Javascript: how to dynamically create nested objects using object names given by an array
Instead of calling
assign(obj, keyPath, value)
example of usage of the previously answer:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
That will output:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
The result would be:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
Edit:
Figured it out.
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}

JSON.stringify(object) incorrect

Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].

Categories

Resources