How to get the first value in a javascript array - javascript

I want to get first file name (Apple_Desk_1920 x 1200 widescreen.jpg) in the array img declared below. How do I do this?
This is my code:
var img = [{
"image" : "Apple_Desk_1920 x 1200 widescreen.jpg"
}, {
"image" : "aa.jpg"
}, {
"image" : "auroracu4.jpg"
}, {
"image" : "blue-eyes-wallpapers_22314_1920x1200.jpg"
}, {
"image" : "blue-lights-wallpapers_22286_1920x1200.jpg"
}, {
"image" : "fuchsia-wallpapers_17143_1920x1200.jpg"
}, {
"image" : "leaves.jpg"
}, ];

It's:
var variableName = img[0].image;
What you have there is an array of objects. To get an array entry, you use [] with an array index (0 to one less than the length of the array). In this case, that gives you a reference to the object. To access an object's properties, you can use literal notation as I have above (obj.image), or using [] with a string property name (obj["image"]). They do exactly the same thing. (In fact, the [] notation for accessing object properties is what you're using when you "index" into an array; JavaScript arrays aren't really arrays, they're just objects with a couple of special features.)
So breaking the line above down:
var variableName = // Just so I had somewhere to put it
img[0] // Get the first entry from the array
.image; // Get the "image" property from it

// dot notation
console.log(img[0].image);
or:
// square-bracket notation
console.log(img[0]['image']);
will get it for you, since you have an array of objects.

Related

Accessing Random Property of Object

I have a huge object that contains the entire ESV Bible. I am trying to get a random book of the Bible whenever I press a button. Here is a small sample of the object.
var esvObject = {
"Genesis": {
"1": {}
"2": {}
"3": {}
},
"Exodus": {
"1": {}
"2": {}
"3": {}
}
}
Here is the code that I am using to get a random book.
var randNum = Math.floor(Math.random() * 66);
var randBook = esvObject[randNum];
var output = randBook;
I would expect this to work, but the output I always get is "undefined," where as I would like the output to be "Genesis" or "Exodus" etc. Getting the random number works, but if
randNum = 1
then
randBook = esvObject[1]
the output returns as "undefined" and I don't know why.
Well the reason you get undefined is that your object is of the structure:
let esvObject = {
bookName: {
1 : {}
}
}
Using bracket [] notation on a javascript object finds the matching key for the name and returns it's value. In your top level object (the one with bookNames for keys), you have to use a valid book name like Genesis. To do so, leverage the Object.keys function of javascript to get an array of all the keys in your object.
You can then use [] notation, which has a different semantic on arrays.
let books = Object.keys(esvObject); // ["Genesis", "Exodus", ...]
let randomKey = books[randNum] // this is an array, so index access works
let book = esvObject[randomKey] // matches on the bookname
And to tie it all together, esvObject["Genesis"][1] would have been valid because the object stored as "Genesis" has a property 1
You are generating random number. And then trying to pick property using that number.
But you object has properties Genesis and Exodus not 1 or 20 etc.
What you need to do is Object.getOwnPropertyNames(esvObject)
that will give you array of the property names. In this case ['Genesis', 'Exodus'] and then you need to pick random element from that array
It would not work because it does not know that the first book is named "Genesis".
To be able to use numbers from the random function you will need to use array from the keys of the object
var keys = esvObject.keys( obj );
randBookKey = keys[randNum]
randBook = esvObject[randBookKey]
esvObject (as you show it) does not have any integer keys. So you need to select a random (existing) key instead:
esvObject[Object.keys(esvObjects)[Math.floor(Math.random() * 66)]]
You're confusing accessing an array with accessing an object.
An array:
arr = ["genesis", "exodus"]
is accessed like this:
arr[0] // genesis
An object:
obj = { "genesis" : "foo", "exodus" : "bar"}
is accessed like this:
obj["genesis"] // foo
To achieve what you want to do, see Access non-numeric Object properties by index?

how can I add this object in an array?

How can I add {[]} in an array?
#CertainPerformance is correct. You have to have an associated property if you want to have objects.
var a = [ { propertyName : [] } ]
then you can access that array like this :
a[0].propertyName or a[0]['propertyName']
And you can have multiple values inside the object too :
var a = [
{
propertyName_1 : [],
propertyName_2 : "",
propertyName_3 : 3,
}
];
var a = [{}] // no problem, you are assigning an empty object `{}` as first element of array
var a = [[]] // no problem, you are assigning an empty array `[]` as first element of array
var a = [{[]}] // Not working because you're assigning empty array into object
//object needs key to store value
var a = {[]} //Not ok <<======== have you ever see var a = { 1, 2, 3} ?
Please refer to documentation:
An object is a collection of properties, and a property is an association between a name (or key) and a value.

how to access object inside an object Array which is inside another array in javascript?

I have an array as follows
[
[{"Id":"5","Color":"White"}],
[{"Id":"57","Color":"Blue"}],
[{"Id":"9","Color":"Brown"}]
]
each object is inside an array which is inside another array. I want to access an object item, let say 'Id' of first object ("Id":"5"). How can I do that?
If the array is assigned to a variable:
var a = [
[{"Id":"5","Color":"White"}],
[{"Id":"57","Color":"Blue"}],
[{"Id":"9","Color":"Brown"}]
];
You can do it like this:
a[0][0].Id;
or
a[0][0]["Id"];
To get the second object you would do:
a[1][0].Id;
or
a[1][0].["Id"];
if it's javascript your object must be named (e.g. x)
Then select the index of the first array (here : 0, 1 or 2)
Then the "small" array content only one item, you have no choice, take 0.
For end, you can pick the property you need, Id or Color.
You have :
var myColor = x[1][0]["Color"];
console.log(myColor); //output : Blue
var obj_c = [
[{"Id":"5","Color":"White"}],
[{"Id":"57", "Color": "Blue"}],
[{"Id":"9","Color":"Brown"}]
];
console.log(obj_c[0][0].Id);
console.log(obj_c[0][0].Color);

accessing certain rows in json in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
guys i know it is dummy question but i spent a lot of hours and cant reach .. i ha ve json array and i want for example to access the elements of second row which are lname2 fname2 90 feedback2 .. this is the array var json = [ {
"lname" : "lname1",
"fname" : "fname1",
"age" : 10,
"feedback" : "feedback1"
}, {
"lname" : "lname2",
"fname" : "fname2",
"age" : 90,
"feedback" : "feedback2"
}, {
"lname" : "lname3",
"name" : "fname3",
"age" : 30,
"feedback" : "feedback3"
}
You have an array of objects - so iterate the array, access the object properties:
for (var i = 0; i < json.length; i++) {
console.log(json[i].fname);
}
To specifically access the second element of the array, specify the index:
var fname = json[1].fname;
You can access 2nd row by index
json[1]
From what I can see, this variable is not a JSON, but simply a javascript array of objects. To access a data in it, you'll have to use json[X].lname for exemple, where X is the index of the object you want to reach.
A JSON is a string of characters representing different type of data, such as arrays and objects. To decode such a string, you could use JSON.parse().
You can find more informations about JSON here : http://www.json.org/
Hope this helps!
Use the below code
json[1].lname
json[1].fname
json[1].age
json[1].feedback
Also what ever you have posted is not a JSON its an parsed result of JSON. JSON is ultimately a string. all the data is converted into one big string. Later when you parse the json you will get the result as in your post.
Explaining the code
Note that variable json is like var json = [] , this [ ] is used to create a array, Hence the variable json is an array and we can access the elements by inex
Here [1] referes to the index of the array. As your json is an array. We use index numbers to access the elements in the array. And the indexes start from 0. So your second element will be in the index 1, 3rd will be in 2 and so on...
Now json[1] will return the second element so..
json[1] = {
"lname" : "lname2",
"fname" : "fname2",
"age" : 90,
"feedback" : "feedback2"
}
note the { } this refers to an object, this { } is used to create an object. Now to access the property values of the object we use the . operator. hence the code json[1].lname , json[1].fname and so on..

How to access a element in JavaScript array?

I have a JS array:
a = ["a",["b","c"]]
How I can access string "b" in this array? Thank you very much!
You index into an array like this:
a[1][0]
Arrays are accessed using their integer indexes. Since this is an array inside an array, you use [1] to access the inner array, then get the first item in that array with [0].
That is a[1][0]
alert(a[1][0]) // "b"
As there is an alternative way also to access the element in the array which is:
a['1']['0'] //"b"
as array is internally an object so think indexes is a property of that object so
a = ["a",["b","c"]]
can be internally and object keys or property are internally transfer to string so:
a = {
'0' : "a",
'1' : ["b", "c"]
}
this also can refactor to:
a = {
'0' : "a",
'1' : {
'0' : "b",
'1' : "c"
}
}
so we can access that index as:
a['1']['0']
this will give the value as b.

Categories