JavaScript push to array - javascript

How do I push new values to the following array?
json = {"cool":"34.33","alsocool":"45454"}
I tried json.push("coolness":"34.33");, but it didn't work.

It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.

var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
Your variable is a javascript object {} not an array [].
You could do:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
and
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Later, you add those objects to your array: array.push (o, o2);
Also JSON is simply a string representation of a javascript object, thus:
var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again

That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);

object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Object vs Array: JavaScript

Use the push() function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
];
// append multiple values to the array
arr.push("Salut", "Hey");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
"Salut"
"Hey"
];
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Will print:
Hi
Hello
Bonjour
Hola
Salut
Hey
Update
If you want to add the items of one array to another array, you can use Array.concat:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Will print
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

Related

How do I create an object from two array indexes?

I am trying to create a javascript object with two array indexes, but it does not seem possible. Why is that? For example:
var arr = ["name","john"];
var obj = {arr[0]:arr[1]}
Computed property names need brackets [myPropName]
var arr = ["name","john"]
var obj = {[arr[0]]:arr[1]}
obj.name // 'john'
You can also do Object.assign,
var arr = ["name","john"];
var obj = {};
var newObj = Object.assign(obj, {[arr[0]]: arr[1]});
console.log(newObj);
If you use arr[0] then js will understand that the property name is arr[0] not "name", so you need [arr[0]] for it to interpret as "name"
var obj = {[arr[0]]:arr[1]}

Converting object containing list of data to json array

My for loop looks like this,
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
console.log(myObj[key]);
}}
output on console looks like this,
car1
car2
car3
i want to convert this data something like this,
$scope.myArray = [{"cars":car1}, {"cars":car2}, {"cars":car3}]
how can I convert it this way in javascript?
You can use var json = JSON.stringify(jsObject) and var jsObject = JSON.parse("json string")
Just iterate over object and push it into array:
var myObj = data.response.carTypes;
var myArr = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
myArr.push(myObj[key]);
}
}
console.log(myArr);
You can convert the array to JSON using var myJsonArray = JSON.stringify(myArray).
If you're doing this conversion in an older browser, you can use a script.
In order to get your array from the JSON you created, you can use:
var myArray = JSON.parse(myJsonArray)
Also, bear in mind that when you use the same key for several objects in your JSON, the last key with the same name is the one that is going to be used.
Here you have to use javascript object.
say
$scope.myArray = [];
var carlist.cars="";
var carlist={};
carlist is a object which cars is a property
then you can try this way:
var myObj = data.response.carTypes;
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carlist.cars=myObj[key];
myArray.push(carlist);
console.log(myArray);
}}
You just need to create a new array and push a new object to it in each iteration:
$scope.myArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
$scope.myArray.push({cars:myObj[key]});
}
};
Demo:
var myObj = {
a: "Car1",
b: "Car2",
c: "Car3"
};
var carsArray = [];
for (var key in myObj) {
if (myObj.hasOwnProperty(key)) {
carsArray.push({cars:myObj[key]});
}
};
console.log(carsArray);

JSON.stringify serializes to [[]]

If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));​

declare hashmap in javascript with <String,String array>

I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?
If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);

What does [] mean in JavaScript?

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?
var openTollDebug = [];
it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate
// let's overwrite the Array object
Array = function(id) {
this.id = id;
}
var a = new Array(1);
var b = [];
console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false
console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true, but it does on b
b.push(2);
console.log(b); // outputs [2]
It means an array.
var openTollDebug = [];
declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:
var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
It's an empty array, and is equal to
var openTollDebug = new Array();
It is shorthand for empty array. Same as new Array().
Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.
It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:
openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};
As an array, you can add items:
openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Many languages have constructs for literals. The [] is an Array literal.
var openTollDebug = [];
is the same as
var openTollDebug = new Array();
Just know that using [] preferred for performance reasons.
There are other literals like Object literals
var MyObject = {
name:'default',
age:22,
hobbies:["golf","video games","otherstuff"]
}
Notice the array literal with data. The [] creates an empty array.
Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it
var b = [] //it is an array literal.

Categories