Length property not updating on object arrays - javascript

Two problems consider the following object:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
Why does my cars array have length of 0? Do i have to update the length property manually?
Why is my stringified object empty when it has parameters in it i'm assuming it is tied into the length property?
Fiddle:https://jsfiddle.net/wcd7f8Lz/

car is initialized as an array, but used as an Object. and an object does not have length attribute...
To get the length of an object, you can do ̀̀̀̀Object.keys(obj).length (get the keys list, and because it is an array, it have a length).
But the problem is also that you initialize cars as an array, but use it as Object...
see docs here:
http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_objects.asp
The solution is to initialize it as Object:
//new obj
var obj = {};
obj['cars'] = {}; //And other object
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
But if you want instead a simple array:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars'][1] = "toyota";
obj['cars'][0] = "mazda";
console.log(obj);
console.log(JSON.stringify(obj));
The syntax is ̀array[identifier] = value;
(and not ̀̀̀̀̀array[value] = identifier)
I've updated the fiddle.

obj.cars.length is 0, because you don't push new items in array, but change it properties:
var obj = {};
obj.cars = []; // obj.cars is empty array
obj.cars.toyota = 1; // obj.cars is empty array with a new property toyota
obj.cars.push('mazda'); // obj.cars is array with a new property toyota and one element mazda
console.log(obj.cars instanceof Array,
obj.cars.length,
Object.keys(obj.cars)); // output: true 1 ["toyota"]

Why you don't use it in this way?
var cars = [];
cars.push({name:'toyota', value:1});
cars.push({name:'mazda', value:0})

That's because you aren't using an array (despite declaring it with an array literal), you're using it as an object.
Arrays are just a special case of object, meaning they can have individual properties. These properties don't exist "in" the array but instead are properties "of" the array.
var arr = [1, 2, 3];
arr.thing = 'a';
console.log(arr.length); // 3
To add elements to an array, you should use push:
var arr = []; // length: 0
arr.push(1); // length: 1
If you want to be able to access an object both by name and index then you can combine push with custom properties.
var arr = [];
arr.push(0);
arr.mazda = 0;

Related

JS- How to convert an array with key and value pairs to an object?

var arr = [];
arr['k1'] = 100;
console.log(arr); //o/p - [k1: 100]
arr.length; //o/p - 0
window.copy(arr); //copies: []
I want to convert this array-like object to a proper obj i.e,
arr = { k1: 100}
So doing window.copy(arr) should copy {k1:100}
NOTE- I need to do this as Node.js express server returns empty arrays in response for such cases.
You can use object spread syntax to copy all own enumerable properties from the original object to a new object:
const arr = [];
arr['k1'] = 100;
const obj = { ...arr };
console.log(obj);
This works even if arr is originally an array, rather than a plain object, because the k1 property exists directly on the array.
(But ideally, one should never have code that assigns to arbitrary properties of an array - better to refactor it to use an object in such a situation to begin with)
var array = []
array["k1"] = 100;
var newObject = Object.assign({},array);
console.log(newObject);

Assigning id number as key of an array creates thousand other array with keys less than given nubmer

I want to group some array by number (idGrupy variable - integer) - in this case the number is 3355.
My code:
if (rezerwacjePosortowanePoGrupie['zgrupa'] === undefined) {
rezerwacjePosortowanePoGrupie['zgrupa'] = new Array();
}
if (rezerwacjePosortowanePoGrupie['zgrupa'][idGrupy] === undefined) {
rezerwacjePosortowanePoGrupie['zgrupa'][idGrupy] = new Array();
}
rezerwacjePosortowanePoGrupie['zgrupa'][idGrupy].push(item);
}
JS does this:
You should use an object, instead of an array as default value.
rezerwacjePosortowanePoGrupie['zgrupa'] = rezerwacjePosortowanePoGrupie['zgrupa'] || {};
By using an array you get a sparse array with holes inside, because the greatest index increases the lenght of the array, if the array is smaller before.
var array = [],
object = {};
array[5] = 42;
object[5] = 42;
console.log(array); // sparse array with undefined
console.log(object);

Pushing data into an array within a 2d array at specific index

var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
arr now looks like this -> [key, Array(1)]
New data comes into barr how to i push another item into the nested array for the same key?
expected output should be something like this: [key, Array(2)]
Option #1:
You can push into the barr array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
barr.push('key2', 'key3');
console.log(arr);
barr is a reference to the array, and when you pushed it into your arra array you actually put there the reference, so when updating barr your reference is still there (and updated).
Option #2:
You can push into the array that is in the 2nd place of your array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
arr[1].push('key2', 'key3');
console.log(arr);
The way you did it the "key" is actually just another value in the array (at index 0). If you want to use a string as the key you'll have to use an object. You can set and get properties using the bracket syntax. The bracket syntax works with arrays as well, but only using integers as keys.
var obj = {};
var barr = [];
var key = "key1";
obj[key] = barr;
// barr changed
obj[key] = barr;

Sort object properties by name like another array

how can I sort object properties by name using another array as refer?
var json = '{"b":90,"c":42, "a":34}';
var obj = JSON.parse(json);
var sorting = ["a","b","c"];
I would like to have obj properties ordered just like sorting array
Thank you
Bye
var sorting = Object.keys(obj).sort();
Javascript objects are not ordered. So, you cannot actually sort them.
Why not just iterating over the array, and then access obj properties ?
for ( var i = 0; i < sorting.length; ++i ) {
var current = obj[ sorting[ i ] ];
// other stuff here...
}
If you don't intent to iterate over the obj, please explain your actual needs.
Convert Object to Array
var jsonArray = [];
$.each(myObj, function(i,n) {
jsonArray.push(n);
});
Sort Array
var jsonArraySort = jsonArray.sort();
Convert Array to Object
var jsonSort = {};
for(var i = 0; i < jsonArraySort.length; i++) {
jsonSort[i] = jsonArraySort[i];
}
You could try something like:
var sorted = []
for (i = 0; i < sorting.length; i++) {
if (json.hasOwnProperty(sorting[i])) {
sorted.push(json[sorting[i]);
}
}
/* sorted will equal [34, 90, 42] */
You cannot order the keys of an object, as per definition,
An ECMAScript object is an unordered collection of propertiesES3 Specs
The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.
Properties of the object being enumerated may be deleted during enumeration. If a property that has not yet been visited during enumeration is deleted, then it will not be visited. If new properties are added to the object being enumerated during enumeration, the newly added properties are not guaranteed to be visited in the active enumeration. A property name must not be visited more than once in any enumeration.ES5 Specs
If you want to a sorted array consisting of your objects keys, you can use [Object.keys][4], To get an array of them, which you can then sort.
var obj = {b:90,c:42, a:34}
console.log (
Object.keys (obj).sort ()
) // ["a","b","c"]
If you are interested in a sorted array, containing both, keys and values, you could do the following.
var obj = {b: 90, c: 42, a: 34},
srt = Object.keys(obj).sort().map(function (prop) {
return {
key: prop,
value: obj[prop]
}
});
console.log(srt) //[{"key":"a","value":34},{"key":"b","value":90},{"key":"c","value":42}]

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