0
How to return values from an object in an array
So I wanted to know how to return object values that are in arrays. So if you make an array called “arr”, and you make 3 objects inside. How do you return the variables stored in the 3 objects?
13 ответов
+ 2
Rishan [da_coder, semi-active]
First get objects from array like this:
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
)
Then get objects value like this:
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
var v1 = obj.v1;
var v2 = obj.v2;
)
See the example here:
https://code.sololearn.com/Wk9Wo4YTuRDw/?ref=app
+ 2
your question lacks of details...
what is your use case exactly?
does your array contains object wich same constructor and not modified?
what to do if same property names in 2 or more objects?
do you want a flat list (array) of all values without their key? or an object with all keys/values pairs? by overriding same keys or using array as value?
+ 1
Martin Taylor no need, but assigning one object to a variable only make a copy by reference ^^
it may improve the readability of the code ;)
+ 1
Martin Taylor
yes, until property values are also objects, in wich case properties are also copied by reference...
you right: that's a matter of opinion...
but the memory footprint /efficiency is a slightly difference... all the more that accessing array will have a slightler less efficient than a local var. In fact, we doesn't even know how implementation of js engine handle that under the hood, and could even create a temporal copy of the object to access it rather than computong the array slot memory address for each access.
var obj = arr[i];
var v1 = obj.v1;
var v2 = obj.v2;
could be more readable as you give var meaningful names, and above all if you do more than just console.log ^^
however if your target is code shortness, arr[i] could be a few short... but if your target is efficiency, don't rely on js, as micro-optimization is quite impossible, due to difference of implementation between each browser engines/platform ;P
+ 1
pairs = {1: "apple",
"orange": [2, 3, 4],
True: False,
12: "True",
}
print(pairs.get(1, 42))
why is it giving False as output
+ 1
sanu kumar
Because in python 1 means True so dictionary key 1 will be override by key True
0
🅰🅹 🅐🅝🅐🅝🅣 so 1 should be not used as key in dictionary.
0
sanu kumar
1 can be use but if you use True also after key 1 then 1 will be override by True same as opposite True will be override by 1
0
sanu kumar
You should always ask separate question not in someone else question.