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

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]);
});

Related

How do I access a specific element in an Object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I am having a hard time trying to accessing any elements in my object.
Find below my code that accesses the object from the localStorage and prints it out on the browser console:
var test = localStorage.getItem('transactionData');
console.log(test);
The above code yields:
[{Amount":"15,000","payersNumber":"070505788","waitersName":"Agnes"}]
When I try to access the element waitersName as seen in the code below:
console.log(">> " +test.waitersName);
It yields:
>> undefined
How do I access the various elements in my object?
test is an array with an object in it, you'll need to access the array item first with test[0] and that will return the object, which will then allow you to access its properties.
The data you retrieve from localstorage is a stringified version of the Javascript array. You first have to parse it using
var array = JSON.parse(test);
Then get your elements from the parsed array.

How to acces a nested json value when it has no key? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
How can you access a nested json value when the value has no key?
im trying to access the "2019-03-19T22:57:47.972Z" value of this json object:
var json = {"metaData":[{"name":"ACTION_NAME"},{"name":"SENT_RECV_TIME"}],"rows":[["SI_OA_CTPParameters","2019-03-20T06:20:45.704Z"],["SI_OA_CTPParameters","2019-03-21T06:04:08.313Z"],["SI_OA_CTPParameters","2019-03-21T06:01:14.412Z"],["SI_OA_CTPParameters","2019-03-20T06:59:54.875Z"],["SI_OA_CTPParameters","2019-03-20T20:32:50.975Z"],["SI_OA_CloudDataAddress","2019-03-19T22:57:47.972Z"],["SI_OA_CloudDataAddress","2019-03-19T22:56:52.115Z"],["SI_OA_CloudDataAddress","2019-03-19T22:54:28.196Z"] ......
what is can reach rigth now is just json.rows[0], which return:
["SI_OA_CTPParameters","2019-03-21T06:04:08.313Z"]
I tried json.rows[0].[1] but this does not work.
I just need the second value "2019-03-21T06:04:08.313Z", how can I acces it?
You can access nested values using json.rows[0][1], like this:
var json = {"metaData":[{"name":"ACTION_NAME"},{"name":"SENT_RECV_TIME"}],"rows":[["SI_OA_CTPParameters","2019-03-20T06:20:45.704Z"],["SI_OA_CTPParameters","2019-03-21T06:04:08.313Z"],["SI_OA_CTPParameters","2019-03-21T06:01:14.412Z"],["SI_OA_CTPParameters","2019-03-20T06:59:54.875Z"],["SI_OA_CTPParameters","2019-03-20T20:32:50.975Z"],["SI_OA_CloudDataAddress","2019-03-19T22:57:47.972Z"],["SI_OA_CloudDataAddress","2019-03-19T22:56:52.115Z"],["SI_OA_CloudDataAddress","2019-03-19T22:54:28.196Z"]]};
console.log(json.rows[0][1]);
json.rows[0] returns an array. Lets call this array a.
You can reference the elements of an array by their index, thus: a[1] will yield your requested element.
However, renaming the array is not convenient, you can simply substitute the original statement back into the a; thus json.rows[0][1] will work.

Can't force object keys to be integer [duplicate]

This question already has answers here:
Keys in Javascript objects can only be strings?
(8 answers)
Closed 4 years ago.
const obj = {
15: 100
};
for(let key in obj)
console.log(key, typeof(key), typeof(+key))
The result is 15 string number. I'm trying to iterate over object values and put some of them into Map object but types compatibility seems unable to achieve. Am I doing something wrong here or object keys are always strings?
Object.keys(obj)
also returns ["15"]
Object keys are always strings. You can see more about it here:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
For you to be able to achieve what you want you will need to cast the keys back to integers.

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"

How to parse json in javascript having dynamic key value pair? [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 7 years ago.
I want to parse a JSON string in JavaScript. The response is something like
var response = '{"1":10,"2":10}';
How can I get the each key and value from this json ?
I am doing this -
var obj = $.parseJSON(responseData);
console.log(obj.count);
But i am getting undefined for obj.count.
To access each key-value pair of your object, you can use Object.keys to obtain the array of the keys which you can use them to access the value by [ ] operator. Please see the sample code below:
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
Output:
1 : 10
2 : 20
Objects.keys returns you the array of the keys in your object. In your case, it is ['1','2']. You can therefore use .length to obtain the number of keys.
Object.keys(obj).length;
So you need to access it like an array, because your keys are numbers. See this fiddle:
https://jsfiddle.net/7f5k9het
You can access like this:
result[1] // this returns 10
result.1 // this returns an error
Good luck

Categories