How to keep the order of JSON numeric keys in nodejs - javascript

var json = `{"3":0,"2":0,"1":0}`
var obj = JSON.parse(json)
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))
output
{"1":0,"2":0,"3":0}
false
I expect to get it
{"3":0,"2":0,"1":0}
true
How to do

This is because json is an object after parsing and object's keys are not guaranteed to be in order
You can use map & it guarantees the order of the keys

That's not possible. In ES6, the keys are traversed in the following order:
First, the keys that are integer indices, in ascending numeric order.
Then, all other string keys, in the order in which they were added to the object.
Lastly, all symbol keys, in the order in which they were added to the object.
The integer keys are sorted in ascending order irrespective of the order in which they are inserted
var a = {};
a[3] = "three"
a[2] = "two"
a[1] = "one"
console.log(JSON.stringify(a))
Reference
You might also want to read: Does JavaScript Guarantee Object Property Order?

You can use array of objects with guid property
const text = '[{"id":3,"value":0},{"id":2,"value":0},{"id":1,"value":0}]'
const json = JSON.parse(text)
console.log(JSON.stringify(json))

You could spend the keys a dot and by iteratong these keys are in the original insertation order, but not accessable with just the number. This needs a dot as well.
var json = `{"3.":0,"2.":0,"1.":0}`
var obj = JSON.parse(json)
console.log(obj[2])
console.log(JSON.stringify(obj))
console.log(json === JSON.stringify(obj))

Related

Read a value from JSON Array without entity

I need to access the 2.2.10.60 and "bank overdrafts...." value from the following array --
May I ask about how to get it?
Here with my code.
var json=chunk.toString();
var obj = JSON.parse(json);
session.send(obj.clauses[0]);
console.log(obj.clauses[0]);
But I can't get the value of "2.3.10.60" and "Bank overdrafts....".
and the inside the "clauses" array will always change.
I had Solved by my own:
var graph = JSON.parse(json);
for(var i=0;i<graph.clauses.length;i++){
var obj=graph.clauses[i];
console.log(obj);
var clause_id;
var clause_text;
for(var key in obj)
{
clause_id=key;
clause_text=obj[key].toString();
session.send(clause_id+"<br>"+clause_text);
}
}
You could use Array#find and check if the wanted property exist in the object. Then take the object and use an property accessor for the result.
key = '2.2.10.60'
result = clauses.find(object => key in object)[key];
If you are not sure about if the array does not contain any object with this key, take an default object or check in advance if find returns a truthy value (like an object), take this
var key = '2.2.10.60'
result,
temp = clauses.find(object => key in object);
if (temp) {
result = temp[key];
}
For a dynamic approach, you could take a variable for the wanted key.
For getting just the first entry of the object, you could take the entries of index zero. This approach assumes, theat only one key/value pair exists in the object.
var [key, value] = Object.entries(object.clauses[0])[0];
// ^^^^^^^^^^^^ target by destructuring an array
// ^^^^^^ source
// ^^^^^^^ property
// ^^^ index/the first one
// ^^^^^^^^^^^^^^ ^ get all key/value pairs of object
// ^^^ take the first pair only
You can use the Array.find() method and verify if the object keys have the value you need.
clauses.find(object => Object.keys(object).includes('2.2.10.60'))
This will return an array of the first object whose keys include '2.2.10.60'

JavaScript, array A length is 0 but A[key] has value

Here is the code
var A = [];
A['key1'] = 'apple';
console.log(A.length);
console.log(A['key1']);
A.length is 0 in the log.... But I just don't get it, apparently A['key1'] has a value 'apple'. Why A.length is 0?
Your are define A is array .Array is not key and value pair,Object only have key value pair
Check the console.log A its still empty
var A = [];
A['key1'] = 'apple';//its not added because is a array
console.log(A);
console.log(A.length);
If you need to add key value pair Define A as a Object.and find the length using Object.keys(A) .It will create array of the Object keys
var A = {};
A['key1'] = 'apple';
console.log(A);
console.log(Object.keys(A).length);
console.log(A.key1.length)
Better see the Difference between an array and an object?
You are using javascript associative array which don't have the built-in function like length to get the number of properties in the array. So Instead of using length function you can use the following line to get the number of properties in the array.
Object.keys(A).length

How to make associative array with number as string in Javascript

I have a code :
var index = 100;
var arr =[];
arr[index.toString()] = "Hello"
The result : index still known as integer not a string. Anyone can explain what's wrong with my code?
You have to declare associative arrays using {}, which creates a new object, because in JavaScript, arrays always use numbered indexes.
You need to declare an object: var arr={};
arrays use numbered indexes.
objects use named indexes.
var index = 100;
var arr ={};
arr[index.toString()] = "Hello";
console.log(arr);
How to make associative array with number as string in Javascript
JavaScript doesn't have associative arrays in the sense that term is frequently used. It has objects, and as of ES2015 (aka "ES6"), it has Maps.
The result : index still known as integer not a string. Anyone can explain what's wrong with my code?
The index variable's value is still a number, yes, because you haven't done anything to change it. But the index in the array is a string (and would be even if you didn't use .toString()), because standard arrays aren't really arrays at all1, they're objects with special handling of a class of properties (ones whose names are strings that fit the spec's definition of an array index), a special length property, and that use Array.prototype as their prototype.
Here's proof that array indexes are strings:
var a = [];
a[0] = "zero";
for (var name in a) {
console.log("name == " + name + ", typeof name == " + typeof name);
}
That said, you don't want to use an array when you want a generic object or map.
Here's using a generic object for name/value mappings:
var o = Object.create(null);
var name = "answer";
o[name] = 42;
console.log(o[name]); // 42
The property names in objects are strings or (as of ES2015) Symbols. I used Object.create(null) to create the object so it wouldn't have Object.prototype as its prototype, since that gives us properties (toString, valueOf, etc.) that we don't want if we're using the object as a map.
Here's using a Map:
var m = new Map();
var name = "answer";
m.set(name, 42);
console.log(m.get(name)); // 42
The main advantages Maps have over objects are:
Their keys can be anything, not just strings or Symbols
They're iterable, so you can use for-of to loop through the mappings they contain
Maps have a size property telling you how many entries they have
Maps guarantee that iteration of their entries is performed in the order the entries were added to the map
With ES6, you could use a Map, which holds any type as key.
var map = new Map;
map.set(100, "Hello");
map.set('100', "Foo");
console.log(map.get(100)); // 'Hello'
console.log(map.get('100')); // 'Foo'
console.log([...map]);
JavaScript does not support arrays with named indexes, in JavaScript, arrays always use numbered indexes.
If you use a named index, JavaScript will redefine the array to a standard object.
After that, all array methods and properties will produce incorrect results.
As you can see in the following example:
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
console.log(x);
var y = person[0]; // person[0] will return undefined
console.log(y);

How to remove all undefined keys from a javascript array (hopefully when creating the array?)

I have placed my frustrations into a jsfiddle to observe here: http://jsfiddle.net/8ShFr/1/
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
alert('why does this array have a length of ' + brand_new_array.length + '???');
I am doing some calculations client side that require me to set javascript array keys of 1M+ in number.
Not knowing exactly what that number is demands that I iterate through the first 1M+ empty array values before getting to an array key that holds data.
I simply want to set a single large key value for a javascript array without creating a bunch of empty keys before it?
I am using jQuery.each to iterate over the array, and it keeps going through array[0], array[1], array[2], etc... when I only set array[123125] for example.
Just filter out the undefineds.
brand_new_array = brand_new_array.filter(function(n){return n !== undefined});
The reason for the length being 10 is that an array's length is set to the largest index number in the array. However, this does not mean there are 9 other values in there because in javascript an array is at its base an object.
The length is just a property in the object. Arrays in javascript are at their core objects (Array Object 1). They merely act like arrays through an api.
"Whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index" 1
1. ECMAScript Language Specification 15.4 Array Objects
You probably want to just use an object with strings for keys (the keys can be the toString() of Numbers, which will happen automatically if you try to use numbers).
var sparse_array_obj = {};
sparse_array_obj[10003210234] = 4; // Fair dice roll
sparse_array_obj[5] = 17; // Truly random number
sparse_array_obj[900] = Math.random(); // Pseudorandom number
for(var i in sparse_array_obj)
console.log(sparse_array_obj[i]);
The downside is that Javascript provides no guarantees about the iteration order through an object (since its keys are unordered by definition). There are however ways around this, such as:
// Sort the keys in numeric order
var sorted_keys = Object.keys(sparse_array_obj).sort(function(a, b){ return a - b; });
for(var i = 0; i < sorted_keys.length; i++)
console.log(sparse_array_obj[sorted_keys[i]]);
Object.keys needs to be shimmed in older browsers.
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
var result = brand_new_array.filter(function(e) { return e != undefined;})[0];
alert(brand_new_array.indexOf(result));
Travis J is right. The array in your example only contains one entry, but your use of jQuery.each() is making you think there are 10 entries because it iterates from 0 up to the highest index number of the array (defines the length). This is from the jQuery.each() API documentation.
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
Going back to your example:
var brand_new_array = new Array();
brand_new_array[10] = "random array value";
This will result in only one console.log output:
for(var i in brand_new_array)
console.log(brand_new_array[i]);
This will result in 10 console.log outputs:
$(brand_new_array).each( function(i,e) { console.log(e) })
Similarly, this will result in 10 console.log outputs:
for (var i=0;i<brand_new_array.length;i++)
console.log(brand_new_array[i]);
If you really want to stick with using .each() then you can skip the undefined indices like so:
$(brand_new_array).each( function(i,e) {
if (this.hasOwnProperty(i)){ console.log(e) }
})
Filter the falsy items - including undifined:
var a=[1,2,"b",0,{},"",NaN,3,undefined,null,5];
var b=a.filter(Boolean); // [1,2,"b",{},3,5]
The length is 11 because the index starts at 0.
x[0] = undefined
x[1] = undefined
x[2] = undefined
x[3] = undefined
x[4] = undefined
x[5] = undefined
x[6] = undefined
x[7] = undefined
x[8] = undefined
x[9] = undefined
x[10] = "random array value"

Can Javascript objects be accessed like arrays?

Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?
The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];

Categories