JSON and reference [duplicate] - javascript

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.

Related

Accessing object values within array within object [duplicate]

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

can we use arr[key:value] in javascript?

In so many Javascript libraries and Angular plugin, I have seen the use of JS array like this:
var arr = ['size':20, 'Active', 'role':'user'];
(This is just an example how they use key and values)
I searched for javascript array but it looks different so how can we use this type of array?
Short answer: You can't write it like this because of the javascript syntax. You can still achieve this, but you shouldn't.
Long answer:
Arrays are considered as objects in Javascript. So you can do this for example :
var array = [];
array['size'] = 20;
console.log(array['size']);
It will work because the array works like any other objects. But you shouldn't do it. It will just confuse your code. Use a plain object to do that:
var obj = {'size':20, 'Active': undefined, 'role':'user'};

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.

jQuery Get associative array Key from index

My question is the following, in an array:
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
How do I get the associative key of an array if I have its index number? Let's say I want associative key of arr[0]'s associative key ( => 'abc'), or associative key of arr[1] '=> 'def'). How is this possible in jQuery?
Let's be clear, I am not looking for the value and I do not need to use $.each(). I just need to link 0 to 'abc' and 1 => 'def' etc... Unfortunately something like arr[0].assoc_key() doesn't seem to exist T_T
Thanks a bunch.
All right so the solution is pretty simple, you need to create an object which associates indeces with keys as well as keys with values. Here is a JSBin that works. Please note that to add an element, you need a custom function (addElement in this case) to be able to have both indeces and keys associated at the right places. This is a rough draft to give you an idea of how it can be done!
JSBin
If you have any question or if that wasn't exactly what you expected, simply edit your question and I'll have another glance at it. It HAS to be a custom made object if you want the behavior you asked for.
Javascript doesn't have a native Dictionary type, you would have to write it. – T McKeown
It isn't possible and jQuery doesn't come into the picture at all. If you use an array as a dictionary like that, you are doing something wrong. – Jon
rethink the way you are doing it. Maybe try array[0] = {key: 'abc', value: 'value1'} – Geezer68
#Geezer68, objects do not support multidimentional data, the array I'm working on is 3 levels deep (I know I didn't says so in my original post, but I didn't think it was relevant).
Anyway, thank you guys, it answers the question! I will rethink it then ;-)
EDIT: I guess I'll just add a level:
var array = new Array();
array[] = 'abc';
array[0] = 'value1'
I don't know an other than using a for ... in. So here how i do it and hope you get a better answer (because i want to know aswell!).
var array = new Array();
array['abc'] = 'value1';
array['def'] = 'value2';
var listKeys = [];
for(x in array) listKeys.push(x);
console.log(listKeys); // ['abc', 'def']
but using [string] on an array object is adding property to the object, not the array. So it may be better to initialise it like that :
var array = {};
You might learn more information on this technique in this question and some restriction on why you should not rely on that.

How can I update one field of an array when given another array containing the state of the field to update?

I have a variable containing an array of answers looking like this:
var answers = [
{"answerId":5,"text":"<p>xx</p>","correct":null,"response":true},
{"answerId":6,"text":"<p>yy</p>","correct":null,"response":false},
{"answerId":7,"text":"<p>zz</p>","correct":null,"response":false},
{"answerId":8,"text":"<p>aa</p>","correct":null,"response":false},
{"answerId":9,"text":"<p>bb</p>","correct":null,"response":false},
{"answerId":21,"text":"<p>cc</p>","correct":null,"response":false}];
and another variable containing an array of responses:
var reply = [
{"answerId":5,"correct":true},
{"answerId":6,"correct":false},
{"answerId":7,"correct":false},
{"answerId":8,"correct":false},
{"answerId":9,"correct":false},
{"answerId":21,"correct":false}];
How can I update the answers variable with the correct responses for each answerId ? So that the null's are replaced?
If we know that the indexes and answers are the same (otherwise we can sort them). A simple for loop can handle this.
for(var i=0;i<answers.length;i++){
answers[i].correct = reply[i].correct;
}
Fiddle

Categories

Resources