Javascript multidimensional array not working - javascript

How to create multidimensional array??
I tried it so far:
var post_data = [];
var id = 1;
post_data[id] = [];
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data);
the above code is not giving me the key. Whats wrong?
DEMO FIDDLE
i want a output something like this:
[1]=> array
(
"name": "abc",
"date": "01-03-2014",
"country": "India",
)
How to get the above output???

To get wished result you can change
var post_data = [];
to
var post_data = {};
and
post_data[id] = {};

You are trying to make an array of object.
Try this : -
post_data[id] = {};

You are using the inner array as an object. The properties that you set on the array still is there, when you display it only the array items are shown.
You should use an object instead of an array, as you are not using the array as an array:
post_data[id] = {};
Instead of setting the properties after creating the object, you can set them when you create it:
post_data[id] = {
name: 'abc',
date: '01-03-2014',
country: 'India'
};

In the third line of code you have to write
post_data[id] = new Array();
So the entire code section looks like
var post_data = [];
var id = 1;
post_data[id] = new Array();
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data[id]['name']);
This should fix it, best of luck :)

Related

Setting nested object properties in JavaScript

How would I add a "property" to an object? I tried: players[data.id].name = data.name;
but it's not working.
Edit: this worked, thanks for the help guys!:
players[data.id] = {name: "Johnny"};
What I want to achieve: (data.id is already defined)
var players = {};
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id].name]); ---> Johnny
welcome to stackoverflow ! You need to define what players[data.id] is first.
Then you can assign data to it. In your example, you are only logging the name property of your object, remove the .name to show the whole object.
let data = { id: "test" };
var players = {};
players[data.id] = {}
players[data.id].name = "Johnny";
players[data.id].age = 13;
console.log(players[data.id]);
First, you have to declare 'players[data.id]' as an object.
The flow of the code would be like
var players = {};
players["dataId"] = {};
players["dataId"].name = "Johnny";
players["dataId"].age = 13;
console.log(players["dataId"].name);

How can I create an array from an input string using JavaScript?

Currently I have a PHP page returning some values. The data is something like this:
08-30-2018, in
08-29-2018, out
08-28-2018, in
08-27-2018, in
How can I create a custom array in Javascript with the values above to be similar as this array below:
var system = [
['08-30-2018', 'in'],
['08-29-2018', 'out'],
['08-28-2018', 'in'],
['08-27-2018', 'in']
];
I have tried array.push, but it does not create an array like above.
What should I do? Can you help me? Thank you!
You can use multi-dimensional arrays in JavaScript
var system = [];
var output = "08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in";
var items = output.split("\n");
for(i=0; i<items.length; i++){
var data = items[i].split(",");
var item = [];
item.push(data[0].trim());
item.push(data[1].trim());
system.push(item);
}
console.log(system);
You could also parse this kind of input using regular expressions:
const input = '08-30-2018, in\n08-29-2018, out\n08-28-2018, in\n08-27-2018, in';
const regex = /(\d{2}-\d{2}-\d{4}), (in|out)/g;
let system = [];
let match;
while ((match = regex.exec(input)) !== null) {
system.push([match[1], match[2]]);
}

How to add data to a 2-D map in Javascript

I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript

Insert array's into hash jquery

I have an array like ["2","3"] to user_id:["2","3"] and another array like ["4","5"] to admin_id:["4","5"] to a hashlike
total_users:user_id:["2","3"],admin_id:["4","5"]
Like this is this possible in jquery??
Thanks in Advance
Try this code.
var userIds = ["2","3"];
var adminIds = ["4","5"];
var obj = {};
obj.total_users = {
user_id: userIds,
admin_id: adminIds
};
alert(JSON.stringify(obj));

Setting dynamically an Object in JavaScript

It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}

Categories