Javascript two dimensional object array - javascript

I'm trying to define arrays of objects, I can define one dimensional array of object but as I try to define the two dimensional I get a error. What is the correct way to define a multidimensional array of objects in Javascript? Here's my code :
for(var i=0;i<3;i++)
{
obj1[i] = [
{property1},{property2}
];
for(var j=0;j<2;j++)
{
obj2[i][j]= [
{property1},{property2}
];
}
}

I think you want:
for (i=0;i<3;i++) {
f[i]=new Array();
for (j=0;j<2;j++) {
f[i][j] = appropriate property ;
}
}

Thanks for all the help, the answer is using it like this:
var obj1 = new Array();
var obj2 = new Array();
for(var i=0;i<3;i++)
{
obj1[i] = [
{property1},{property2}
];
var obj2[i] = new Array();
for(var j=0;j<2;j++)
{
obj2[i][j]= [
{property1},{property2}
];
}
}

Related

Javascript 2D array getting each element

I have a 2D array that looks like:
var example = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];
I'd like to iterate through the array and take out 'V1.0' and 'V2.0' and store them in their own new array, and do the same for '1' and '2'. I need to break the data up for use with Chart.js
My loop looks like this:
var labels = [];
var data = [];
for (var i=0; i<example.length; i++) {
labels.push = (example[i][0]);
}
for (var j=0; j<example.length; j++) {
data.push = (example[0][j]);
}
I don't know how to properly get either element into their own array for use later.
You can use map to do this, and shift the result in order to remove the first occurence.
var example = [
['Version', 'Number'],
['V1.0', 1],
['V2.0', 2]
];
var result = example.map(e => e[0])
console.log(result);
From what I saw into your example the first pair of elements are the keys for your data, into your example will include them into your final arrays.
This example will generate to a dictionary with the keys Number and Version containing the corresponding values from your array.
var example = [['Version', 'Number'], [ 'V1.0', 1 ], [ 'V2.0', 2 ]];
function extract(items) {
var keys = {},
version = items[0][0],
number = items[0][1];
keys[version] = [];
keys[number] = [];
return items.slice(1).reduce(function(acc, item) {
acc[version].push(item[0]);
acc[number].push(item[1]);
return acc;
}, keys);
}
var result = extract(example);
console.log(result);
From this point you can do something like:
var labels = result.Version;
var data = result.Number;
This looks like what you are trying to achieve:
for(var i=0; i<example.length; i++){
labels.push(example[i][0])
data.push(example[i][1])
}

Javascript multi-dimension array initialization

I'm looking for the best way to initialize multi-dimensional arrays in Javascript. I'm much more familiar with PHP where I'm not obliged to declare arrays or dimensions before feeding it with values.
Basically what I tried to do is create an array with the following format
catalogue[i]["name"]="a name";
catalogue[i]["description"]="a description";
...etc...
If I do the following:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i]['name']=otherarray[i];
}
Catalogue is undefined, I also tried with catalogue[i].name but same issue. If I only assign a simple value like catalogue[i]=2, it works but that's not what I'm looking for. I couldn't find a working example of what I'm looking for.
Do I need to initialize every possible dimension of an array before being able to feed it with new values?
Thanks
Laurent
var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue[i] = {};
catalogue[i]['name'] = otherarray[i];
}
Or
var catalogue = new Array();
for (i = 0; i < otherarray.length; i++) {
catalogue.push({"name":otherarray[i]});
}
Put this in your loop to create the object you want to store the values in:
catalogue[i] = {}; OR catalogue.push({});
Your code would be like this then:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {}; // initialization
catalogue[i]['name']=otherarray[i];
}
Note that you can initialize and assign a value in the same line:
var catalogue = new Array();
for (i=0; i<otherarray.length;i++)
{
catalogue[i] = {
name: otherarray[i],
otherKey: 'otherValue' // list all of your keys and values
};
}
If you want string keys in your array in Javascript you have to declare an Object. The catalogue variable itself is an array but each element inside that array is an object with the two keys "name" and "description". For example this code works :
var c = [1,2,3,4,5];
var n = ['one', 'two', 'three', 'four', 'five'];
var cat = [];
for (i = 0; i < c.length; i++)
{
cat[i] = {
name : n[i],
value: c[i]
};
}
now if you console.dir(cat); it outputs this result :
Array[5]
-> 0 : Object
name: "one"
value: 1
-> 1 : Object
name: "two"
value: 2
...

Push from one array to another by reference

Given this fiddle, does anyone have a suggestion as to how I might update the indices of array1? Or more to the point, any idea how to make the indices of array2 references to indices of array1?
http://jsfiddle.net/y8rs56r3/
var array1 = [
{num:"one"},
{num:"two"},
{num:"three"}
];
var array2 = [];
var i = array1.length;
while(i--){
if(i!=1)array2.push(array1[i]);
}
array2[0].num = "one updated";
console.log(array2);
console.log(array1);
Obviously, in this codeblock, array1[0] is not updated.
since your array is set of objects try like this:
var array1 = [
{num:"one"},
{num:"two"},
{num:"three"}
];
var array2 = [];
for(x in array1){
array2.push(array1[x]);
}
array2[0].num = "one updated";
console.log(array2);//output [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]
console.log(array1);// output [Object { num="one updated"}, Object { num="two"}, Object { num="three"}]

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});

An array converting question

I have an array below,
var array = {
"Id":[1,2,3],
"Name":["one","two","five"],
"row":[8,9,7]
}
but I want to transform it into
var array2 =
{"data":
[
{"Id":1,"Name":"one","Row:8"},
{"Id":2,"Name":"two","Row:9"},
{"Id":3,"Name":"five","Row:7"},
]
}
Is this possible?
This should do it:
// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
// Note that array.Id = [1,2,3] does not result in corresponding keys
// array.Id[0] corresponds to value 1!
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
Row: array.Row[i]
});
}
var array2 = {data: []};
for (i in array.Id) {
array2.data.push({
Id: array.Id[i],
Name: array.Name[i],
row: array.row[i]
});
}
Didn't test it
it's not an array. it's an object.
var myArr = [1,2,3]; //Array definition
var myObj = {test:"1",test2:"2"}; //Object Definition
var array = [1,[1,2,3]]; // multidimensional array

Categories