Retrieving values from JSON object - javascript

I have an xml file that has been converted to the json listed below. I have been trying to figure out how to retrieve -Name and -Value from each of the Attributes with no luck. I'm guessing I need to create a sub-object that is equal to jsonobj.Media.Attribute[i], but am unable to access -Name or -Value once I do that. Any suggestions?
jsonobj= {
"Media": {
"Attribute": [
{
"-Name": "Keywords",
"-Value": "keyword value"
},
{
"-Name": "Title",
"-Value": "title value"
},
{
"-Name": "Description",
"-Value": "description value"
},
{
"-Name": "Author",
"-Value": "author value"
},
{
"-Name": "Copyright",
"-Value": "copyright value"
}
]
}
};

This will alert all the values you're looking for:
var list = jsonobj.Media.Attribute
for(index in list)
{
var obj = list[index];
var name = obj["-Name"];
var value = obj["-Value"];
alert(name);
alert(value);
}

Iterate jsonobj.Media.Attribute and use ['-Name'] to retrieve the value
for(var i = 0; i < jsonobj.Media.Attribute.length ; i++)
{
var attr = jsonobj.Media.Attribute[i]
alert(attr["-Name"]);
alert(attr["-Value"]);
}

You can not use - in the code, cause it is an operator, and JS will not recognize it as a method.
To solve your problem you can access the properties using other way.
Otherwise your code:
jsonobj.Media.Attribute[i].-Name
You can use:
jsonobj.Media.Attribute[i].["-Name"]
What is the same from calling, for an example:
jsonobj.["Media"].Attribute[i].["-Name"]

It can not identify key Attribute. Says can not read property 'Attribute' of undefined.

Related

Trying to get the object key of a nested JSON object

I need to get a list of all the key names in the following JSON object:
var myJSON = [
{
"Employees_Name": "Bill Sanders",
"Work_plan_during_my_absence": "Work from home",
"Assigned To-Manager Approval": [
"mymanager#gmail.com"
],
"AbsenceVacation_Summary": [
{
"Computed_Leave_Days": 2,
"From_Date": "2018-08-20",
"To_Date": "2018-08-21",
"Id": "Shccbcc230_a30f_11e8_9afa_25436d674c51"
}
],
"Leave_Type": "Work from Home",
"Reporting_Manager": "My Manager",
"Total_Days": 2,
}
]
When I use the Object.keys method, it retrieves only the top level key names:
var keys_arr = Object.keys(myJSON[0]);
console.log(keys_arr);
The result is an array:
"[ 'Employees_Name', 'Work_plan_during_my_absence', 'Assigned To-Manager
Approval', 'AbsenceVacation_Summary', 'Leave_Type', 'Reporting_Manager',
'Total_Days']"
The key names that are missing are the ones inside of 'AbsenceVacation_Summary'.
I think what I need to do is loop through the array of names returned and see if the value is an object or an array...but I don't know how to do this. Please advise.
You're right you need to walk your object structure recursively to discover nested objects and collects their keys:
function collectKeys(inputObject, outputKeys) {
if (Array.isArray(inputObject)) {
for(let i = 0; i < inputObject.length; i++) {
collectKeys(inputObject[i], outputKeys);
}
} else if (typeof inputObject === 'object') {
Object.keys(inputObject).forEach(function(key) {
outputKeys.push(key);
collectKeys(outputKeys[key], outputKeys);
});
}
}
var collectedKeys = [];
collectKeys(myJSON, collectedKeys);
Working fiddle here
Result will show in console
References
javascript typeof
javascript Array.isArray
javascript Array.forEach

How to change value of JSON using for loop/ foreach?

I've tried to change the value of json depending on key, but my loop not work
here's the code:
var duce2 = [{
"pages": "foo1",
"hasil": ""
},
{
"pages": "foo2",
"hasil": ""
},
{
"pages": "foo3",
"hasil": ""
},
{
"pages": "foo4",
"hasil": ""
},
{
"pages": "foo5",
"hasil": ""
},
{
"pages": "foo6",
"hasil": ""
}
];
for (let key in this.duce2) {
console.log("jalan ga fornya");
if (this.duce2[key].pages == 'foo2') {
console.log("jalan ga ifnya");
this.duce2[key].hasil = '1';
}
}
console.log(duce2);
did i doing something wrong with the code above? the console.log doesn't appear on for and if
EDIT : my chrome dev console just showing this
I am not sure why you use "this.duce2" in your code.
However, some useful advices :
variables should be declared using the least permissive scope. Instead of declaring the array with "var", you should prefer "const"
arrays should not be traversed using the for...in construction (which is for object properties). Instead, you should prefer to use the forEach method.
The result would be:
const duce2 = [ ... ];
duce2.forEach((elem) => {
if (elem.pages === 'foo2') {
elem.hasil = '1';
}
});
Use duce2 instead of this.duce2,
You can iterate like this.
for (var key in duce2) {
if (duce2.hasOwnProperty(key)) {
if(duce2[key].pages=='foo2'){
//your code ,what needs to be done.
}
}
}
The for/in statement loops through the properties of an object.
Hope it helps..!

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

Accessing JSON array's through object properites

Let's say I have the next JSON file:
{
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
}
I want to access the rating of a show, by it's name. Something like this:
var rating = data.shows["House of cards"].rating;
Is this possible? Or something similar?
Thanks a lot!
You won't have such hash-style access just by deserializing that JSON sample.
Maybe you might be able to re-formulate how the data is serialized into JSON and use object literals even for shows:
{
"shows": {
"House of cards": {
"rating": 8
}
}
}
And you can still obtain an array of show keys using Object.keys(...):
Object.keys(x.shows);
Or you can even change the structure once you deserialize that JSON:
var x = { shows: {} };
for(var index in some.shows) {
x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}
// Accessing a show
var rating = x.shows["House of cards"].rating;
I suggest you that it should be better to do this conversion and gain the benefit of accessing your shows using plain JavaScript, rather than having to iterate the whole show array to find one.
When you use object literals, you're accessing properties like a dictionary/hash table, which makes no use of any search function behind the scenes.
Update
OP has concerns about how to iterate shows once it's an associative array/object instead of regular array:
Object.keys(shows).forEach(function(showTitle) {
// Do stuff here for each iteration
});
Or...
for(var showTitle in shows) {
// Do stuff here for each iteration
}
Update 2
Here's a working sample on jsFiddle: http://jsfiddle.net/dst4U/
Try
var rating = {
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
};
rating.shows.forEach(findsearchkey);
function findsearchkey(element, index, array) {
if( element.name == 'House of cards' ) {
console.log( array[index].rating );
}
}
Fiddle
var data = {"shows": [{"name": "House of cards","rating": 8},{"name": "Breaking bad","rating": 10}]};
var shows = data.shows;
var showOfRatingToBeFound = "House of cards";
for(var a in shows){
if(shows[a].name == showOfRatingToBeFound){
alert("Rating Of "+ showOfRatingToBeFound+ " is " +shows[a].rating);
}
}

Extract a section of many objects in an array

If I have array of objects like this
[
{
"name" : "some name",
"more data" : "data",
...
},
{
"name" : "another name",
"more data" : "data",
...
},
...
]
And I want to copy the array, but only the name element in the object so that I have this:
[
{
"name" : "some name",
},
{
"name" : "another name",
},
...
]
Is there a short hand way to do this without writing a loop?
No, you have to do this with a loop, but in can still be short:
for(var i = 0; i < arr.length; i++)
arr[i] = {name: arr[i].name};
If you use any sort of framework or library all it will do is hide the loop from you. It will still loop through everything.
Example
No, there is no way of doing this without a loop. Can I suggest you do this with a bit of prototyping magic. (Note, this can be done with some map or forEach magic which just hides away the fact that you're looping. I'll leave this with the loop to illustrate the idea)
Array.prototype.clone = function(predicate)
{
var newArray = [];
for(var i = 0;i <this.length; i++){
var newElement = {};
for(x in this[i]){
if(predicate(x)){
newElement[x] = this[i][x];
}
}
newArray.push(newElement);
}
return newArray;
}
This allows you to clone an array, passing in a function that decides which property to keep from each element in the array. So given an array like:
var arr = [
{
"name" : "some name",
"more data" : "data"
},
{
"name" : "another name",
"more data" : "data"
}
];
You can do
var newArray = arr.clone(function(x){ return x == "name";});
Which will return you an array with the same number of objects, but each object will just have the name element.
Live example: http://jsfiddle.net/8BGmG/

Categories