Accessing object values within array within object [duplicate] - javascript

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I'm trying to process data from the OpenWeather API for multiple cities. This is what the data looks like:
{
"cnt":20,
"list":[
{
"coord":{"lon":-99.13,"lat":19.43},
"sys":{"country":"MX","timezone":-18000,"sunrise":1591012665,"sunset":1591060290},
"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],
"main":{"temp":12.88,"feels_like":11.84,"temp_min":12.78,"temp_max":13,"pressure":1027,"humidity":82},
"visibility":8047,
"wind":{"speed":1.5,"deg":60},
"clouds":{"all":20},
"dt":1591013691,
"id":3530597,
"name":"Mexico City"},
{...next cities...}
]
}
I'm fine with everything, except the weather part(3rd line). I want to assign each value to a separate variable like so:
weatherid = 801
main = "Clouds"
description = "few clouds"
I've tried stuff around the lines of
main = citydata.list[i].weather.main; (doesn't work)
main = citydata.list[i].weather.main(); (doesn't work)
main = Object.values(citydata.list[i].weather);
and quite a few things in between.
(Well, the last one kinda does something but I don't end up with something different, and when I try and get the values it's always "undefined")
So, what's the simplest way of accessing that data and storing each part of it in its own variable.
Or even just converting the contents of "main" into an array (I'm assuming those questions overlap)
Thanks!

try that:
const data = JSON.parse(req.data);
const main = data.list[0].weather.main

Related

Array.fill a 2x2 array, then trying to set arr[0][0] = true fills the entire column? [duplicate]

This question already has answers here:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
(7 answers)
Closed 5 years ago.
I was doing some DFS stuff and wanted to use array that was the same size as the original matrix to toggle whether nodes were visited. I noticed when I tried to set the node as visited visited[r][c] = true, it ended up setting the entire column. I realized this only happens with Array(numberOfRows).fill(Array(numberOfCols).fill(false)).
Was wondering why it does that, and if there's a better way to initialize a 2D array with a set number of rows/cols?
var foo = [
[false,false],
[false,false],
];
foo[0][0] = true;
var bar = Array(2).fill(Array(2).fill(false));
bar[0][0] = true;
console.log(foo); // [[ true,false],[false,false]] (what I expected)
console.log(bar); // [[ true,false],[true,false]] (wtf?)
In the first case you have created two separate arrays with [] syntax, which are separate references to the separate objects. But the case is another with Array#fill.
Array#fill works with a single value. When you pass an array into the fill function to fill the outer array, only single array is created and its going to fill all items in the outer array. This means that two references of the single array are inserted in the outer array.
We can see it comparing the references of the first and second array.
var bar = Array(2).fill(Array(2).fill(false));
console.log(bar[0] === bar[1]);

JSON and reference [duplicate]

This question already has answers here:
JSON find in JavaScript
(7 answers)
Closed 7 years ago.
I receive data as a JSON object, like this:
[{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}]
I know I can access the data like this:
alert(obj[0].amount);
But I would like to be able to access the data like this:
obj[transid].amount
where transid is a previously declared and assigned variable, like this:
var transid = 1091;
alert(obj[transid].amount); //returns -549
If this is even possible, I assume the JSON object would have to be restructured (I don't have any control over how I receive the JSON object), but I don't really have any idea how to go about this. I've tried Googling and SOing, but I am just not sure what to look for.
Edit: I've looked at the proposed duplicate question as suggested by Travis J, and I do not agree that this is a duplicate. I'm not asking to loop through data. I'm asking for methods to reference by a specific index, given JSON that I don't control how it comes to me. The accepted answer in the proposed duplicate shows how I envision the code to look (in the second code box), but I don't think it really answers my question. Another answer in the proposed duplicate, posted by Hakan Bilgin, suggests using defiantjs, which would probably work. However, there are many other methods, some of which have been provided as answers to this question already.
You can use filter like
obj.filter(function(o){
return o['transid'] === 1091;
})[0].amount // -549
You can add the above function to Array's prototype like
Array.prototype.get = function(id){
return Array.prototype.filter.call(this,function(obj){
return obj['transid'] === id;
})[0].amount
}
And use it like
obj.get(1091); // -549
It is up to you to add proper validation like dealing with not found keys and duplicates.
You can create a new object from that one. Something like this
var transactionArray = [
{"transid":1091, "payee":"McDonalds", "amount":-549},
{"transid":1092, "payee":"McDonalds", "amount":-342},
{"transid":1093, "payee":"McDonalds", "amount":371}
];
var transactionsById = {};
transactionArray.forEach(function(element) {
transactionsById[element.transid] = element;
});
var transid = 1091;
alert(transactionsById[transid].amount); //returns -549
Where transactionArray is what you refer to as obj in your question.

Can't access items in javascript array [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 7 years ago.
My array is:
{
"data":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
"name":"splash.png",
"imageOriginalWidth":1024,
"imageOriginalHeight":768,
"imageWidth":1969,
"imageHeight":1477,
"width":800,
"height":600,
"left":-585,
"top":-406
}
and I have two variables:
$image_data = $array['data'];
$image_name = $array['name'];
Both of these variables return undefined
Am I missing something obvious?
First off, it's important to note that this is not an array, it's an object definition.
An array can be defined as:
[
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
"splash.png",
1024,
768,
1969,
1477,
800,
600,
-585,
-406
]
Which is doesn't the keys, like "data": (which can also be expressed as data:) It seems you definitely want to access values by key, so what you really want is:
var data, name, myObject;
// NOTE: We do not "quote" object keys under normal circumstances.
myObject = {
data:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACCCCAAAIIIICAvwIEIP760zoCCCCAAAIIIIAAAoES+P992sgQ2E6rdwAAAABJRU5ErkJggg==",
name:"splash.png",
imageOriginalWidth:1024,
imageOriginalHeight:768,
imageWidth:1969,
imageHeight:1477,
width:800,
height:600,
left:-585,
top:-406
}
data = myObject["data"]; // We don't usuaully use this
name = myObject["name"]; // style, although it works.
//
// It's generally reserved for
// dynamic access.
//
// i.e. we make a string to match the keyname.
However, to be correct you should use dot syntax to access the object key.
data = myObject.data;
name = myObject.name;
I hope this has cleared things up a little for you.
On a side note DO NOT use names like $array. First don't use the $ prefix for normal variables, this isn't PHP or BASIC.
Secondly, when you have an object, you want it to be named something that is useful / meaningful / memorable. (naming things is hard!)
When you name things properly, other people can read and understand your code, and after a heavy weekend on the town, so can you.
Have you tried declaring the array and also the variables you wanna store the store the stuff from array to, using the var keyword?
E.g:
var myArray = ["hello",["world"];
By looking at your code I have the impression that you were trying to make a custom object.

JSON using parse or stringify correctly [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
This is what I'm getting from server
['model':{"category":[{"id":1}],"food":[{"id":1}].... // long json here
How can I use jquery/javascript to parse to get category id and food id? I tried to use
JSON.parse(data)
or
JSON.stringify(data)
And after that, doing
$.each(data, function (i, x) {
it will give me each letter of all array. How can I parse it correctly, getting the ids that I want?
JSON.parse(data) will turn the data you showing into a JavaScript object, and there are a TON of ways to use the data from there. Example:
var parsedData = JSON.parse(data),
obj = {};
for(var key in parsedData['model']){
obj[key] = parsedData['model'][key]['id'];
}
Which would give you a resulting object of this:
{category:1, food:1}
This is based on the limited example of JSON you provided, the way you access it is entirely dependent on its structure. Hopefully this helps get you started, though.
You want to use JSON.parse(), but it returns the parsed object, so use it thusly:
var parsed = JSON.parse(data);
then work with parsed.

Javascript JSON Array [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am using a get request from a server API and I am making a request and then doing this:
var resp = JSON.parse(response);
I call to the server providing 0001 & 0002 as arguments and
after the JSON.parse it returns an array such as:
{"0001":{"id":1},"0002":{"id":2}}
I know that traditionally if i were given static responses such as
{"placeID":{"id":1},"placeID":{"id":2}}
I could do this:
resp.placeId.id
but given that the return names aren't always the same how can I access that first value resp.0001.id given that 0001 may not always be the value returned?
Use a for...in loop.
for(var property in resp) {
console.log(property + ": " + resp[property]);
}
You can access the "0001" element of the response like this:
resp["0001"].id
Since you say that you're providing the id in the query, you presumably have it stored in a variable somewhere.
If you really want to access the first element in the response, you can't use JSON.parse, because you'll lose the ordering information once you suck that data into an object. And if you have to care about the order of the elements, then that JSON is badly-formed, and should be using an array instead of a top-level object.

Categories

Resources