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

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"

Related

how to access values in javascript's object? [duplicate]

This question already has answers here:
Setting and getting object to local storage using stringify?
(4 answers)
Closed 8 months ago.
I am trying to iterate through the values in an object.
Here are the values of the object:
object=Object.values(localStorage)[0];
console.log(object);
Output
{"name":"e7","id":"7","category":"n"}
I tried:
console.log(object[0]);
But it printed just "{"... Then I tried... object[name], object['name'] , object[0][0]... but the output is not satisfactory...
I want to loop through these values like I want to access "name" and its value and so on...
Can I loop through individual values of JavaScript?
the output is actually a value ..
Local storage can only store strings, so what you get from it is just a JSON string and you have to parse it into a JavaScript object before you can use it like one.
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
You can do it by calling JSON.parse() (documentation here).
var fromLocalStorage = '{"name":"e7","id":"7","category":"n"}';
// Parse the JSON string from localStorage into a JS object
var object = JSON.parse(fromLocalStorage);
// Get a single property
console.log(object.name);
// Loop all the key-value pairs of the object
Object.keys(object).forEach(function(key) {
console.log(key + ' -> ' + object[key]);
});

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

How to convert a String that looks like JSON or a JS object, to an actual JS object? [duplicate]

This question already has answers here:
How to parse JSON easily?
(3 answers)
Closed 6 years ago.
The String I am talking about was initially a part of a JS object like:
var nameVal = "Jacob";
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
var aJSObject = {
"name" = nameVal,
"favNumbers" = favNumbersVal
};
The variable I am interested in is favNumbersVal. Please notice that the starting and ending " around the value of favNumbersVal are the normal double quotes we put around a String whenever we define a String.
The format of the value of favNumbersVal is coming from a library dynamically.
The question is that how do I convert the value of favNumbersVal to a JS object, so that when I later convert sJSObject to JSON using JSON.stringify(), the value of aJSObject becomes a JSON object, and the value of favNumbers becomes a JSON object nested inside the aforementioned JSON object.
Using JSON.parse():
var favNumbersVal = "{\"firstNum\":0, \"secondNum\":1, \"thirdNum\":2}";
console.log(JSON.parse(favNumbersVal));

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

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 = {}

Json object to key value pairs [duplicate]

This question already has answers here:
Fastest way to flatten / un-flatten nested JavaScript objects
(17 answers)
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to convert
var connection = {
someName:'someValue'
}
to
data:{'connection.someName':'someValue'}
how can i do that?
To elaborate more;
I have
var data ={connection : {name : 'SomeName', url:'SomeUrl'}}
and i post
$.ajax({
type : 'POST'
data : data
....
})
and my back-end expects form data like
connection.name='SomeName'
connection.url='SomeUrl'
so it can bind connection data to Connection bean
Thanks.
Whilst the result you are looking for is technically valid JSON, this will not parse as expected:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x.data.someName;
// Error: x.data is undefined
This is because the parser treats the entire literal as a single key, so you would have to access the value like so:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x["data.someName"]
// "someValue"
What you actually want in order to be compliant, parsable JSON is this:
{"data":{"someName":"someValue"}}
The parser will treat this appropriately:
var x = JSON.parse("{\"data\":{\"someName\":\"someValue\"}}");
x.data.someName;
// "someValue";

Categories