Get information from varying objects in JSON - javascript

I have this code (which is variant thought the time) in JSON
{
"5780": {
"app": "Bye",
"name": "Hello World",
"surname": "Friend"
},
"6654": {
"app": "Hello",
"name": "Hi",
"surname": "godbye"
}
}
I want to get the information from each section (for example the "app" section) an insert in a js variable. The problem is that the object title (5780 & 6654) change will change (at the same time, the sections information). So I need something like section[1].app = jsvariable1

You can loop
var obj = {
"5780": {
"app": "Bye",
"name": "Hello World",
"surname": "Friend",
},
"6654": {
"app": "Hello",
"name": "Hi",
"surname": "godbye",
}
}
for (var key in obj) {
console.log(obj[key].app);
}
This will log
Bye
Hello
If you want to update the value of app:
for (var key in obj) {
obj[key].app = "New Name";
}
The key is the 5780 and 6654

First of all, your json is not valid so you have to check it(as i did in the code below) . So here's what i did :
var sections = {
"5780": {
"app": "Bye",
"name": "Hello World",
"surname": "Friend",
},
"6654": {
"app": "Hello",
"name": "Hi",
"surname": "godbye",
}
};
var index = [];
//setting the index array
for (var x in sections) {
index.push(x);
}
console.log(sections[index[0]].app)
console.log(sections[index[1]].app)

Related

How to get specific array from JSON object with Javascript?

I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.

Printing JSON properties

I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is
[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]
I want to be able to access the lang_code property of every single language and send it. I've tried to use
var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}
Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?
On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".
Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
var body = [{
"lang_code": "eng",
"site_language": "1",
"name": "English"
}, {
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
}, {
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
}];
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>
I looped through your lang_codes like this:
var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];
for(var i = 0; i < codes.length; i++) {
console.log(codes[i].lang_code);
}

Merge geojson based on unique ID

I'm a beginner in Javascript so please exuse this probably dumb question. I want to merge two json files based on unique object id.
Number one look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},
{"id": "3876803",
"properties": {"name":"another name"...}}...]
Number Two looks like this:
"features": [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"}},
{"id": "3876803",
"properties": {...}}]
The Elements in the second Json are not in the same order and not all elements of the first file exist in the second.
The Result should look like this:
"features": [{
"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}},{
"id": "3876803",
"properties": {
"name":"another name",
"description": "some description",
"website": "afancywebsite"}}]
I started coding this but I have no idea how to get it working...
for(var i in json1.features){
for (var z in json2.features){
if (json1.features[i].id===json2.features[z].id){
json1.feature[i].properties = json2.features[z].properties}}}
This will do the job:
var features = [
{"id": "3876802",
"properties": {
"name": "some name",
"facts": "some facts"}
},
{"id": "3876803",
"properties": {
"name":"another name"
}
}
];
var features2 = [{
"id": "3876803",
"properties": {
"description": "some description",
"website": "afancywebsite"
}
}
];
features.map(function(feature){
var matchedArray = features2.filter(function(feature2){
return feature2.id === feature.id;
});
if(matchedArray && matchedArray[0]){
for(var attr in matchedArray[0].properties){
feature.properties[attr] = matchedArray[0].properties[attr];
}
}
});
We start by using Array.map() to run through the 'features' array, one by one.
Then we use Array.filter() on the features2 array which gives us an array containing the only object in features2 (matched[0]) which has the same id as feature.id.
If there's a match, then we run through the 'properties' in the features2 object using a 'for in' loop and copy them to the 'feature' object.
If you want to get advanced info about this check out this stackoverflow question: How can I merge properties of two JavaScript objects dynamically?. For example, if you're writing bullet-proof javascript you should use 'hasOwnProperty' in a for in loop.
You may also want to guard against properties in 'features2' overwriting a property with the same name in 'features'.
However if you would like to keep your code more or less as it was this also works:
for(var i in features){
for (var z in features2){
if (features[i].id===features2[z].id){
for(var attr in features2[z].properties){
features[i].properties[attr] = features2[z].properties[attr];
}
}
}
}

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

How to create JSON using Javascript with sets of data?

I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal
You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.

Categories