Can you create an associative array in JavaScript? [duplicate] - javascript

This question already has an answer here:
JSON Stringify Removing Data From Object
(1 answer)
Closed 6 years ago.
I am trying to set up an associative array in JavaScript and then store it in HTML5 Local Storage:
var student = [];
student["david"] = "He is doing very well";
localStorage['student'] = JSON.stringify(student);
var data = JSON.parse(localStorage['student']);
alert(data.david);

There is no such thing as an "associative array" in JavaScript. You are using a regular array which requires the use of numeric indexes, and adding arbitrary properties to it, which are ignored when you serialize the array to JSON.
The JSON-stringified result will be: "[]".
You need to use a real object:
var student = {}

Related

Array to json using javascript [duplicate]

This question already has answers here:
JavaScript associative array to JSON
(5 answers)
Closed 4 years ago.
I am trying to pass an array through jQuery's ajax. The problem is that when I try to pass the array created in JavaScript to JSON, it returns something empty. I even try console.log, but when I try to convert it to JSON there is nothing. Here is a representation of how I do it:
var data = [];
data['name'] = 'test';
data['mail'] = 'test';
data['pass'] = 'test';
console.log(JSON.stringify(data)); // result []
Every array is an object. You are assigning object properties with the data['name'] = 'test' syntax. Arrays are indexed with integers and they "must" be in sequence. try a[0] = 'foo'. or Array.push

Get from JSON object with string IDs to JS numeric IDs [duplicate]

This question already has answers here:
Is there any way to use a numeric type as an object key?
(11 answers)
Closed 4 years ago.
i have a JSON object (sent from php) and I want to convert the IDs to a numeric key using JS. So currently it looks something like that:
let foo = {"66":"test","65":"footest"};
And now I want it to look like this:
let foo = {66:"test",65:"footest"};
Object keys do not need to be numerical to be accessed - as noted in the comments - they are strings regardless.- Below, I am console logging the "66" property using the brackets notation - foo[66]
let foo = {"66":"test","65":"footest"};
console.log(foo[66]); // gives "test"
// if you want to assign values numerically - ie using the index of a loop - then you could do
for(i = 63; i<65; i++) {
foo[i] = "test" + i;
}
console.log(foo); // gives {"63": "test63", "64": "test64","65": "footest","66": "test"}

Struggling with Javascript Object Array adding keys [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}

How to get key values from "array string" in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Extract values from json string javascript
(3 answers)
Closed 6 years ago.
I have an array in Laravel controller like:
$succeeded[] = array('name' => $name,
'file' => $file
);
...
return $succeeded;
I use an ajax call for getting $succeeded, and I'll have a return string in js function composed of:
"[{"name":"sor.jpg","file":"399393.jpg"}]"
My question is how can I get "name" and "file" values from the string above?
Note: I didn't use any JSON object in controller, but returned just the array. However I wonder it is advantageous to use JSON object.
You first need to parse the response text into a JSON array using the native JSON.parse, and then you can extract the values from the object in the parsed array using dot notation.
var respText = "[{\"name\":\"sor.jpg\",\"file\":\"399393.jpg\"}]";
var arr = JSON.parse(respText)[0]; // Careful - this will throw on invalid JSON
var name = arr.name; // "sor.jpg"
var file = arr.file; // "399393.jpg"

copying an array of objects in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Copying array by value in javascript
How to copy an array of objects to another array in Javascript?
var qwerty1 = arr;
var qwerty2 = arr;
Both qwerty1 and qwerty2 may look different but point to the same reference.
I read somewhere that "assigning a boolean or string to a variable makes a copy of that value, while assigning an array or an object to a variable makes a reference to the value." So my two arrays post different operations return the same objects.
Any light in this regard?
The idiomatic way to copy an array in Javascript is to use concat:
var qwerty1 = arr.concat();
var qwerty2 = arr.concat();

Categories