Weird data lose in javascript while converting Array into Object - javascript

I was just working with JavaScript objects and found this which i cant figure out . I created an array with few values and trying to convert that array into object using spread and new in JavaScript but for my surprise only the first value in the array is been put into the object with its type .
I have no need what exactly is happening in background
let array = [1970,1,1]
let object = new Object(array)
console.log(object)
Output :
NumberĀ {1970}
I was expecting {1970 , 1 , 1} object but actual output is
NumberĀ {1970}

to convert array to object use Object.assign
Object.assign({},[1970,1,1])
or you can populate the object with the array elements
let array = [1970,1,1];
var obj = new Object();
Array.prototype.push.apply(obj, array);
console.log(obj);

The closest thing you could do is:
const object = {...array}
Which will give you the output:
{0: 1970, 1:1, 2:1}

You can try with Object.assign()
let array = [1970,1,1];
let object = Object.assign({}, array);
console.log(object);

It works in the Chrome (Version 75).
Check the following code, if in case you are expecting the following behavior.
CODE:
let array = [1970,1,1];
let obj = {}, i = 0;
for(var element in array) obj[i++] = array[element];
console.log(obj);

Related

JSON stringify does not convert array [duplicate]

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

Casting an object to an Array using Array.from

I'm trying to create an ArrayBuffer from a WebSocket's stringified data.
The stringified data is a Float32Array.
Here's what I attempted:
var parsed = JSON.parse(streamData);
var arrayed = Array.from(parsed);
var arr32 = Float32Array.from(arrayed);
var kbuff = new ArrayBuffer(arr32);
The variable parsed looks like this:
But then my Array.from results in an empty array:
What am I missing here?
And - Is this the proper way of creating my ArrayBuffer?
Array.from() requires the object to have a length property. Use Object.values() instead:
const parsed = {
0: 'a',
1: 'b',
2: 'c',
}
const arrayed1 = Array.from(parsed);
const arrayed2 = Object.values(parsed);
console.log({ arrayed1 });
console.log({ arrayed2 });
For Array.from need to iterable argument with property length.
Try to use Object.values(parsed) for getting array from your parsed values and then use Float32Array, seems it's can help you.
Or you can get array from pais [key, value] use Objest.entries(parsed)

How to create number object property name dynamically using javascript with integer key?

I need to generate a object with number object property using javascript new Object().
For example I want to create a object dynamically by the below format
{1:"1",2:"2",3:"5"}
I tried below
var json_str=new Object();
$([1,2,3]).each(function(i,t){
var str="'json_str."+t+"="+t+"'";
eval(str);
});
But it is not created object like that, if it is string value it will create.
You could use Object.assign and map the objects.
var array = [1, 2, 3],
object = Object.assign(...array.map(k => ({ [k]: k.toString() })));
console.log(object);
Simple JS:
let array = [1, 2, 3];
let object = {};
for (let num of array) {
object[num] = String(num);
}
console.log(object);
console.log(Object.keys(object)); // your keys will automatically become strings too
You should avoid using eval() where-ever possible to prevent accidental injection exploits.
I think you want to make this an Array, then you can
push objects onto it:
var json_str=new Array();
$([1,2,3]).each(function(i,t){
json_str.push( { [t] : t });
});
json_str: Array(3)
0:{1: 1}
1:{2: 2}
2:{3: 3}

Get the value of an object with an unknown single key in JS

How can I get the value of an object with an unknown single key?
Example:
var obj = {dbm: -45}
I want to get the -45 value without knowing its key.
I know that I can loop over the object keys (which is always one).
for (var key in objects) {
var value = objects[key];
}
But I would like to know if there is a cleaner solution for this?
Object.keys might be a solution:
Object.keys({ dbm: -45}); // ["dbm"]
The differences between for-in and Object.keys is that Object.keys returns all own key names and for-in can be used to iterate over all own and inherited key names of an object.
As James Brierley commented below you can assign an unknown property of an object in this fashion:
var obj = { dbm:-45 };
var unkownKey = Object.keys(obj)[0];
obj[unkownKey] = 52;
But you have to keep in mind that assigning a property that Object.keys returns key name in some order of might be error-prone.
There's a new option now: Object.values. So if you know the object will have just one property:
const array = Object.values(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const array = Object.values(obj)[0];
console.log(array);
If you need to know the name of the property as well, there's Object.entries and destructuring:
const [name, array] = Object.entries(obj)[0];
Live Example:
const json = '{"EXAMPLE": [ "example1","example2","example3","example4" ]}';
const obj = JSON.parse(json);
const [name, array] = Object.entries(obj)[0];
console.log(name);
console.log(array);

How to clone an array in javascript without using JSON.stringify or JSON.parse? [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I have an array example fruit . I'd like to copy it as array fruits2, without keeping reference.
As in the following example reference is kept so fruits is modified.
var fruit = function (name){
this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('orange'));
var fruits2 = fruits;
fruits2.length = 0;
console.log(fruits);
http://jsfiddle.net/vkdqur82/
Using JSON.stringify and JSON.parse does the trick but the objects in fruits2 are not any longer of type fruit but are of general type object
var temp = JSON.stringify(fruits);
var fruits2 = JSON.parse(temp);
I would like to know an alternative approach which would keep inner object of fruit.
Use slice: var fruits2 = fruits.slice(); should do it.
Your jsFiddle, modified
See also: MDN
**Edit. I was a bit lazy, let's correct my answer to make up for that.
For an Array of just values slice is perfect. For an Array of objects or arrays or a mix of values/objects/arrays, the Array and Object elements of the Array to clone need cloning too. Otherwise they will be references to the original arrays or objects (so: not copies) and a change of one [of these references of arrays or objects] will be reflected in all 'clones' containing a reference to it.
To clone an Array of Arrays/Objects/mixed values Array.map is your friend. There are several methods to think of:
creating a new instance with old data
var fruits1 = fruits.map(function(v) {return new Fruit(v.name);});
using JSON
var fruits2 = fruits.map(function(v) {return JSON.parse(JSON.stringify(v));});
create and use some cloning method
var fruits3 = fruits.map(function(v) {return cloneObj(v);});
In case 3, a method for cloning could look like:
function cloneObj(obj) {
function clone(o, curr) {
for (var l in o){
if (o[l] instanceof Object) {
curr[l] = cloneObj(o[l]);
} else {
curr[l] = o[l];
}
}
return curr;
}
return obj instanceof Array
? obj.slice().map( function (v) { return cloneObj(v); } )
: obj instanceof Object
? clone(obj, {})
: obj;
}
Using this cloneObj method, Array.map is obsolete.
You can also use var fruitsx = cloneObj(fruits);
The jsFiddle from the link above is modified to demonstrate these methods.
For Array.map, see again MDN
slice can do the trick.
You can also use .map but .slice is normally faster.
var copy = fruits.map(function(item) {return item});
Hope it helps
You can declare a new array and use concat method, so that you concat all values from your array to the new array. Something like this:
var x = ["a","b"];
var a = [];
a = a.concat(x);
console.log(a);
I edited my poor answer.
Best regards.

Categories