Why won't console.log show my whole javascript multidimensional array? - javascript

When I make an array like this in Javascript:
var tabInfos = [];
tabInfos[1] = [];
tabInfos[1]['label'] = 'one';
tabInfos[1]['id'] = '111';
tabInfos[2] = [];
tabInfos[2]['label'] = 'two';
tabInfos[2]['id'] = '222';
How can I get console.log(tabInfos) to show the first value as well (e.g. 1, 2):

The reason you see the first item as undefined is because it is.
JS Arrays start at 0 and you start yours at 1.
Have a look at the recommended way of getting what you seem to want - an array of objects:
var tabInfos = [{
"label": "zero",
"id": "000"
}, {
"label": "one",
"id": "111"
}, {
"label": "two",
"id": "222"
}];
console.log(tabInfos);
// or if you must
console.log(JSON.stringify(tabInfos));

You should be using objects, not arrays for your internal items. They are not array-like.
var tabInfos = [];
tabInfos[1] = {};
tabInfos[1]['label'] = 'one';
tabInfos[1]['id'] = '111';
tabInfos[2] = {};
tabInfos[2]['label'] = 'two';
tabInfos[2]['id'] = '222';

You achieve this as follows:
var i = 0;
JSON.stringify(tabInfos, null, 2).split(/\n/).forEach(function(line) {
window.console && console.log(
(/\s{2}\S/.test(line)) ? i++ + line : line
);
});

Actually by your screenshot the console DOES show the values of tabInfos[1] and tabInfos[2] first value, it is shown inline right after the minus sign [-] and because there are no values in them nothing appears on the right.

var tabInfos = [];
tabInfos[1] = {};
tabInfos[1].label = 'one';
tabInfos[1].id = '111';
tabInfos[2] = {};
tabInfos[2].label = 'two';
tabInfos[2].id = '222';
but making tabInfos an object instead of array is recommended(then you can make associative array also means you can have named properties).

Are you worried about the first undefined value? JavaScript arrays are 0 indexed. If you set the first value from 1, then the 0th position automatically becomes undefined.

Related

Dynamically create nested javascript objects with the same key but different values from an array

Need help figuring this out..
I want to create nested Javascript Object dynamically..
I have got a key, which has multiple values that needs to be nested per value in an array.
For example:
{
"name": [{
"desc": "A",
"age": 26,
"name": [{
"desc": "B",
"age": 12,
"name": [{
"desc": "C",
"age": 48
}]
}]
}]
}
So far i have this:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]
const name = "name"
var json = {};
var current = json;
for (var i = 0; i < data.length; i++) {
current[name] = data[i];
current = current[name];
}
console.log(JSON.stringify(json));
Which only returns the first item in the data array.
{
"name": [{
"desc": "A",
"age": 26
}]
}
Below code does what you want:
var data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]]
const value = data.reverse().reduce((acc, item) => {
return [{
...item[0],
name: acc
}]
});
console.log(value);
Though if you just had an array of objects instead of an array of arrays containing objects this would be slightly easier:
var data = [{desc:"A", age:26}, {desc:"B", age:12}, {desc:"C", age:48}]
data.reverse().reduce((acc, item) => {
return [{
...item,
name: acc
}]
});
You need to use recursion in this case since your are creating children.
In this code, we reduce the size of the array by removing the first element and passing it back to the same function
var data = [
[{desc:"A", age:26}],
[{desc:"B", age:12}],
[{desc:"C", age:48}]
]
function recursivelyAssignData(array) {
// we get the current element, to assign it a property "name",
const currentElement = array[0][0]
// we remove the first element, so it wont be pass to subsequent call of the function.
array.shift();
// if this is the last element, we don't want to assign the property "name" to it.
return array.length >= 1 ? Object.assign(currentElement, {
// we assign the value of same function, but with a different array.
name: recursivelyAssignData(array),
}) : currentElement;
}
const result = {request: recursivelyAssignData(data)};
console.log('results:', result , 'json:', JSON.stringify(result ));
P.S
Recursion might not be the most intuitive thing in the world, if you have trouble understand it, please ask question.
You are almost there. Since the values are inserted as first item in an array, use index 0 to access them.
const data = [[{desc:"A", age:26}], [{desc:"B", age:12}], [{desc:"C", age:48}]];
const name = "name";
let result = {
[name]: data[0]
};
let obj = result;
for (let i = 1; i < data.length; i++) {
let current = obj[name][0];
current[name] = data[i];
obj = current;
}
console.log(result);

Javascript is empty after filling with data

Javascript array is empty after filling with values
I tried this code:
var browserdata = new Array();
// Fill the array with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata); // This shows an empty array
It should show { "qqq" => "zzz", "zzz" => 1 }
Actual output is [] (empty array).
You need to use Object data type instead of Array. Using object structure, you can assign properties to it and corresponding value for that property to get the desired output as { "qqq" => "zzz", "zzz" => 1 }
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
You can also use the another approach, to assign the property at the time object is declared:
var browserdata = {
'qqq': 'zzz',
'rrr': 1
};
console.log(browserdata);
It will never return empty as there are data in the array, with your code it will return an output
[qqq: "zzz", rrr: 1]
If you want to get an output like { "qqq" => "zzz", "zzz" => 1 } , You should use objects .Objects are nothing but a grouping of data,
for example, consider a student array with different data sets.
here you could define individual data or data sets like
student['name'] = john ;
student['mark'] = 20;
OR
students =[{name : john , mark :20} ,{name : rick, mark :20} ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://javascript.info/array
If new Array() is called with a single argument which is a number, then it creates an array without items, but with the given length.
It’s rarely used, because square brackets [] are shorter. Also there’s a tricky feature with it lets see.
var arr = new Array(2); // will it create an array of [2] ?
console.log( arr[0] ); // undefined! no elements.
console.log( arr.length ); // length 2
var browserdata = new Array();
browserdata[0] = "zzz";
browserdata[1] = 1;
console.log(browserdata);
console.log(browserdata.length);
That solution works for me. Initializing with {} rather than [] or new Array() works. Thanks.
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
Only the positive integer keys of array object are displayed by default, but the rest of the properties can still be accessed and seen in the Google Chrome console.
var arr = []
arr[1] = 1
arr[-1] = -1
arr[.1] = .1
arr.a = 'a'
arr['b'] = 'b'
console.log( arr ) // [undefined, 1]
console.log( arr.b ) // "b"
console.log( { ...arr } ) // { "1": 1, "-1": -1, "0.1": 0.1, "a": "a", "b": "b" }

How can I push an object into an array?

I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))

Uncaught TypeError: data.push is not a function

I am trying to push
data.push({"country": "IN"});
as new id and value to a json string. but it gives the following error
Uncaught TypeError: data.push is not a function
data{"name":"ananta","age":"15"}
Advance Thanks for your reply
To use the push function of an Array your var needs to be an Array.
Change data{"name":"ananta","age":"15"} to following:
var data = [
{
"name": "ananta",
"age": "15",
"country": "Atlanta"
}
];
data.push({"name": "Tony Montana", "age": "99"});
data.push({"country": "IN"});
..
The containing Array Items will be typeof Object and you can do following:
var text = "You are " + data[0]->age + " old and come from " + data[0]->country;
Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.
Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );
So you can iterate and always can get the properties, even if they are empty, null or undefined.
edit
Cool stuff to know:
var array = new Array();
is similar to:
var array = [];
Also:
var object = new Object();
is similar to:
var object = {};
You also can combine them:
var objectArray = [{}, {}, {}];
Your data variable contains an object, not an array, and objects do not have the push function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
Also make sure that the name of the variable is not some kind of a language keyword.
For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
you can use push method only if the object is an array:
var data = new Array();
data.push({"country": "IN"}).
OR
data['country'] = "IN"
if it's just an object you can use
data.country = "IN";
I think you set it as
var data = [];
but after some time you made it like:
data = 'some thing which is not an array';
then
data.push('') will not work as it is not an array anymore.
One things to remember push work only with array[] not object{}.
If you want to add object o inside inside n like that :
a = {
b:"c",
D:"e",
F: {
g:"h",
I:"j",
k: {
l:"m"
}
}
}
a.F.k.n = { o: "p" };
console.log(a);
Try This Code $scope.DSRListGrid.data = data; this one for source data
for (var prop in data[0]) {
if (data[0].hasOwnProperty(prop)) {
$scope.ListColumns.push(
{
"name": prop,
"field": prop,
"width": 150,
"headerCellClass": 'font-12'
}
);
}
}
console.log($scope.ListColumns);
make sure you push into an Array only
and if their is error like Uncaught TypeError: data.push is not a function**
then check for type of data
you can do this by consol.log(data)
hope this will help
let dataArray = [{'id':1,'code':'ABC'},{'id':1,'code':'ABC'},{'id':2,'code':'ABC'}]
let obj = {};
dataArray.forEach(task => {
task.id in obj ? obj[task.employee_id].push(task):
obj = {
...obj,
[task.employee_id]: [task],
}
});

how check and substitute values in an array?

I have an array done with values from some radio buttons, say myArray = ["1","40","35"];
every value has his counterparts, say for instance 1 = "men", 2 = "women", 40 = "red hairs".
what's the best method to build another array where every values gets his counterpart?
so something like that myBrandNewArray = ["men","red hairs", …];
I should store my couples into variables for some maintenance, like
var "1" = "men", "2" = "women", … ;
but I don't know if this is a good approach…
ps. even pointing me to some resources will be great. Thank you.
I would keep a Hash of values
hash = { '1': 'Men', '2': 'Women' ... }
Then [ '1', '2', ... ].map( function(v) { return hash[v]; } );
IE9- will not accpet this, in this case you could just iterate in a for loop
Why don't you use an object as associative array?
var array = new Object();
array["1"] = "men"
array["40"] = "red hairs"
You can create an object like:
var arr = {
'1' : 'men',
'2' : 'women'
}
You can always access this easily like : arr['1'] == 'men'
if you want to create from existing arrays:
say myArray & myBrandNewArray
you can do something like
var arr = {};
foreach ( var i in myArray ) {
arr[myArray[i]] = myBrandNewArray[i];
}
i think this function
myArray = ["1","40","35"];
myBrandNewArray = myArray.map(function(element){ /* your code to get the right array 8/ })
source: http://www.tutorialspoint.com/javascript/array_map.htm
there is also a jQuery (cross browser) version of this function, for more details about that look here jQuery.map(myArray, function(value, index){ /*....*/ })
Use an object:
var val = {
1: "men",
40: "red hairs"
};
alert(val[1]);
alert(val[2])
;
well, finally I did this:
having
var numericalArray = ["1","50","45", …];
and
var couples = { "50" : "homme",
"1" : "femme",
"85" : "court",
…
};
I can call this and get a new array with coupled values:
function assignValues(numericalArray) {
var verbalArray = [];
for (var i=0; i<numericalArray.length; i++) {
var value = numericalArray[i];
verbalArray.push(couples[value]); // right, I can't check if the values exists
}
console.log('here my new array:', verbalArray);
}
thanks to have me pointed on use of an object.

Categories

Resources