accessing certain rows in json in javascript [duplicate] - javascript

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..

Related

Sort an array of objects by a given property order [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Sorting an array of objects by property values
(35 answers)
Closed 4 years ago.
I have this array :
displayedColumns = ['CompanyName','Ticker', 'Id', 'Name', 'ActualTradeDate',
'Spot', 'PreviousTradeDate', 'PreviousSpot', 'FPrice', 'Status']
and an array of objects with the above values as properties :
data : [{Ticker : ".. " ......... Status : "... " } , .... {...} ]
but the properties in the data array are not sorted in the 'displayedColums' order (as wanted )
the end wanted result is :
data = [{ CompanyName : ".. " Ticker : ".."......Status : ".." },
{ CompanyName : ".. " Ticker : ".."......Status : ".." },....
{ CompanyName : ".. " Ticker : ".."......Status : ".." }]
**just to be clear, I am not looking to sort the array by asc/desc values of a certain property. I want to change the order of the properties in the array to 'displayedColumn' order
I am not sure how to sort an array by property order.
thanks a lot
Objects are never sorted, but arrays are. Therefore you could turn your array of objects into an array of arrays, containing the objects values in displayedColumns order:
const result = data.map(obj => displayedColumns.map(key => obj[key]));

Add two json object data in javascript [duplicate]

This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 8 years ago.
I want to add two JSON objects which have structure like this (It has more data and I ignore them in here):
{ "total_count":100 , "types":20 , { "a" : 5 , "b" : 6 }}
{"total_count" : 1 , { "a" : 2 } }
I want to add these objects in node.js in order to get following object:
{ "total_count":101 , "types":20 , { "a" : 7 , "b" : 6 }}
I use mongodb which has $inc function which add current json to existing one in db and reduce load and store load. I'm interested to find a method which handle this action in nodejs.What should I do ( I dont want to do it manually preferly. instead i like to use existing functions)?
something like this? your json structure is not quite correct, so i added x.
object1 = {"total_count":100 , "types":20 , "x": { "a" : 5 , "b" : 6 }};
object2 = {"total_count" : 1 , "x":{ "a" : 2 } };
object1.total_count += object2.total_count;
object1.x.a += object2.x.a;

how to push an object like this in jquery?

may I know how to push var obj= [{}] in .each? for example like this.
$.each(maintasks_row, function(index, maintasks_val) {
obj.push([{
"name" : maintasks_val.task_name,
"desc" : "",
"values" : [{
"from" : "/Date("+maintasks_val.time_start+")/",
"to" : "/Date("+maintasks_val.time_end+")/",
"label": maintasks_val.task_name,
"customClass" : "ganttRed"
}]
}]);
});
I'm using this for $(".gantt").gantt({source: obj});
On this site the var data is [{}] is this an object? and how can I insert it?
thank you
.push does not require you delcare it as an array ( like you tried obj.push([{ - unless of course you are pushing an array into an array
Just simply ...
obj.push({"name" : maintasks_val.task_name, ..
adds a new single item intto the array
Update as comment , yes, declare obj as a typeof array first
var obj=[];
This is now the same as the data array you have shown in your docs example - and we can now .push() into it.

Use for loop to select dom in javascript

it's frustrating that we can't select JSON elements (or really any elements) using a similar code like this:
//An JSON object is parsed into Response beforehand
for(var count = 1; count <= Response.objCount; count ++) {
console.log(Response.obj+count.content);
}
In the code, I want to output a JSON object like this:
{ "objCount" : 2 ,
"obj1" : { "result" : true ,
"content" : "blah blah 1" } ,
"obj2" : { "result" : true ,
"content" : "blah blah 2" } }
But no, we can't use variable as whole or part of an identifier in Javascript..
So, any suggestions on how to handle such JSON objects when I want to output each and every object?
Thank you!
If "Response" is your structure, then you can indeed do what you ask:
for(var key in Response) {
console.log(Response[key].content);
}
You can't loop on "length" because "Response" is not an array, and plain objects don't have a "length" property.
Now, one problem is that you can't be sure that you'll get the components out in any particular order. That is, the loop above may give you "obj2" before you get "obj1". You could address that problem in a couple of ways. First, you could re-think your data structure and store it as an array. Alternatively, you could fetch the keys and sort them, and then iterate through the sorted array of property names.
var keys = Object.keys(Response);
keys.sort(function(key1, key2) {
// comparison ...
});
for (var count = 0; count < keys.length; ++count)
console.log(Response[keys[count]].content);
The Object.keys() function only works in newer browsers, but you can do a similar trick with a for ... in loop to pull out the property names.
edit — with your updated structure that includes an explicit property of your own for the length, you can use a plain for loop:
for (var count = 1; count <= Response.objCount; ++count)
console.log(Response["obj" + count].content);
Use brackets to access the property using the property name as a string:
Response["obj" + count].content

How to get the first value in a javascript array

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.

Categories