How can I add a sub array to an array? - javascript

I'm trying to build an array to create a menu system where each index has 2 objects, a name and a subarray of Strings.
I tried something like this:
var menus = [];
menus.push({title:"Aztec", mySubArray:{"String1", "String2","String3"} });
but that doesnt seem to be the right syntax. any ideas?
thanks

You have a syntax error, mySubArray has to be an array []
var menus = [];
menus.push({title:"Aztec", mySubArray:["String1", "String2","String3"] });

mySubArray is not a valid object, because it's missing property names, which makes it an array. You can fix this by either making mySubArray an array:
mySubArray:["String1", "String2","String3"]
or by adding property names to make it an actual object:
mySubArray:{1: "String1", 2: "String2",3: "String3"}
The issue isn't with the fact that it's a "sub array" being pushed, only with the syntax of the actual mySubArray value.

Related

Getting Key name of an Object item

Before marking this as a duplicate, i've spent a lot of time looking through similar question and most of the answers did not solves my situation.
i have a huge list of items as objects by IDs. like this, in a Map (userDB)
{
"15321":{name:"name1",status:"status1"},modules:{...},
"15322":{name:"name1",status:"status1"},modules:{...},
"15323":{name:"name1",status:"status1"},modules:{...}
}
now i need to make an operation in which i need all these IDs, in that case, the key names of every item on it. i need to get these "15321","15322" etc.
more specifically i wanted something that i could fetch in something like
userDB.forEach( u => {
//something here to get u's key
})
i've tried Object.keys(), but it will return a list of IDs as an object
{"15321","15322"...} in which i still cant grab the ID string
i've tried for (i in Object.keys(userDB)) too, no successs
i double-checked for silly syntax errors and everything of the sort.
Things that will be nice to get in mind to answer this:
dont try to show me a new way of storing stuff, it is already stored so you will not be of help
the result SHOULD be the ID as a string, the name of the key.
dont ask "why i want to make this". just answer and dont try to change this scenario. because this is what i've seen in most of the other similar questions and it is what makes me walk in circles every time.
TL;DR. i just want to get the parent key names of the object im currently processing
Object.keys(obj) will return an array.
But in your data there is another key modules except IDs.
So you can use this :
var keys = Object.keys(data);
keys.pop();
console.log(keys); // ["15321", "15322", "15323" ...]
You might be confused. Object.keys(obj) returns an array. In your case it looks like this: ["15321", "15322", "15323"]. You could iterate through that array like so and you'll have both the key and the object and you'll be able to do with them whatever you want. Below is a for loop that attaches the key to the object as a key named 'key'.
var keys = Object.keys(myObject);
for(var i = 0; i < keys.length; i++){
var key = keys[i]; // this is your key
var obj = myObject[key]; // this is the key's value
obj.key = key;
}
EDIT
In javascript an Array is also an object, but the 'keys' so to speak are usually numbers instead of strings. So an array that looks like this:
["Hello", "there"] is essentially represented like this: { 0 : "Hello", 1 : "there" }
When using for-in on an array, it'll loop through the keys, but those keys will be 0, 1, 2... instead of the items themselves.

Unexpected type cast when pushing key and value into array javascript

I have my empty array
const arr = [];
I want to push 2 things. 1.) a numerical value and 2.) an object
data.push('id':id, 'obj':storedObj);
This throws Unexpected type cast. I was curious if something like this was do-able?
You are trying to add something that looks like a JavaScript object. To add id and storedObj do:
data.push(id, storedObj);
But if you want to identify each one by the keys, define like this:
data = {};
data.id = id;
data.obj = storedObj;
And if you want to insert an object do:
data.push({'id':id, 'obj':storedObj});
you need to push objects into the array. So do something like this
data.push({'id':id}); data.push({'obj':storedObj});
You get to keep the keys

It is possible to assign array 'value key' to a value?

I have an array like this
var list =['lemon', 'apple'];
list['yuck'] = 'durian';
list.forEach(function(i){
console.log(i);
});
The out put is
lemon
apple
So where is durian?
This question is not about how use array properly, I just find it odd that we able to do that, what's really going on here?
forEach iterates on an array's elements, that is the properties identified by a positive integer. 'yuck' is a string which can't be converted to an integer.
If you really want to iterate on all values, you can do this:
for (var key in list) {
console.log(list[key]);
}
But it breaks all the optimizations of arrays. You should probably use a Set or an object instead.
Because that's not how you add a value to a javascript array. You have to use the method Array.prototype.push()
var list = ['lemon', 'apple'];
list.push('durian');
list.forEach(function(i){
console.log(i);
});
list['yuck'] = 'durian';
Here the syntax says add the text durain to a property yuck.
Here you are adding key values. This is how you assign values to a object.
The above line will throw an exception as you cannot add key values to array. So your array is never modified.
And this one
list.forEach(function(i){
console.log(i);
});
You are looping the initial array. Hence same values are printed.
On other hand you can use.
list.push('durian')
Or
list[2] = 'durian'

Creating multi-dimensional arrays in javascript, error in custom function

I was trying to define an array (including other arrays as values) in a single javascript statement, that I can loop through to validate a form on submission.
The function I wrote to (try to) create inline arrays follows:
function arr(){
var inc;
var tempa = new Array(Math.round(arguments.length/2));
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
This is called three times here to assign an array:
window.validArr = arr(
'f-county',arr('maxlen',10, 'minlen',1),
'f-postcode',arr('maxlen',8, 'minlen',6)
);
However in the javascript debugger the variable is empty, and the arr() function is not returning anything. Does anyone know why my expectations on what this code should do are incorrect?
(I have worked out how to create the array without this function, but I'm curious why this code doesn't work (I thought I understood javascript better than this).)
Well from what your code does, you're not really making arrays. In JavaScript, the thing that makes arrays special is the management of the numerically indexed properties. Otherwise they're just objects, so they can have other properties too, but if you're not using arrays as arrays you might as well just use objects:
function arr(){
var inc;
var tempa = {};
for(inc=0; inc<arguments.length; inc=inc+2) {
tempa[arguments[inc]]=arguments[inc+1];
}
return tempa;
}
What you're seeing from the debugger is the result of it attempting to show you your array as a real array should be shown: that is, its numerically indexed properties. If you call your "arr()" function as is and then look at (from your example) the "f-county" property of the result, you'll see something there.
Also, if you do find yourself wanting a real array, there's absolutely no point in initializing them to a particular size. Just create a new array with []:
var tempa = [];
Your code works. Just inspect your variable, and you will see that the array has the custom keys on it. If not expanded, your debugger shows you just the (numerical) indixed values in short syntax - none for you.
But, you may need to understand the difference between Arrays and Objects. An Object is just key-value-pairs (you could call it a "map"), and its prototype. An Array is a special type of object. It has special prototype methods, a length functionality and a different approach: to store index-value-pairs (even though indexes are still keys). So, you shouldn't use an Array as an associative array.
Therefore, their literal syntax differs:
var array = ["indexed with key 0", "indexed with key 1", ...];
var object = {"custom":"keyed as 'custom'", "another":"string", ...};
// but you still can add keys to array objects:
array.custom = "keyed as 'custom'";

jQuery delete array index

I'm having trouble deleting/removing an item from an Array in jQuery. I've run the results in console.log() and it shows up as an Object. I've created a function which returns a json string and then I parses it, an example below:
var ret = jQuery.parseJSON($.return_json(data));
It works nicely, however, I am running an $.each loop which removes items from that array/object.
var old = $("element").find("li[rel=item]");
$.each(old, function(index, value) {
ret.splice($(value).attr("id"), 1);
});
Above, I am searching for elements with attribute rel = item. The same element contains an id which is related to the index of the function which returns the json parsed variable.
I ran Developers Tools in Google Chrome to see the error and it prints:
Uncaught TypeError: Object #<Object> has no method 'splice'
Any words of guidance will be much appreciated. Thanks.
It seems like ret is not actually an array (and likely an object (ex: {someName: "someVal"}) instead).
I'm also making an assumption that you mean for $(value).attr("id") to be a string identifier like someName in the object example above. If that is the case and you are working with an object and you do have the appropriate property identifier, then luckily there is an easier solve than splice.
Try:
$("element").find("li[rel=item]").each(function() {
delete ret[$(this).attr("id")];
});
splice is only a method of arrays, not objects. ret in this case, is an object, not an array.
If you are trying to remove specific elements from an object, you can do this:
$("element").find("li[rel=item]").each(function(i,v){
delete ret[v.id];
});
ps. You can use .each instead of $.each.
If you really want to make the object into an array, you can simply loop through it and push the elements into an array.
var obj = {"1":"item 1", "2": "item 2", "3": "Item 3"};
var arr = [];
for(i in obj){
if(obj.hasOwnProperty(i)){
arr.push(obj[i]);
}
}
ret is the JSON object containing the array, and you can't splice it. You need to reference whatever you called the array within the object and splice that.
(Would help if you posted the code where you define the array).

Categories