How to get specific array from JSON object with Javascript? - 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.

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

How can I store mapping orders in BBDD and then eval them

I'm trying to store in MongoDB one document with an object with the properties I want to map latter. My idea it's to create a function that will receive 2 params. First the object where I got to find the mapping, and second the object where I have to take the info from.
For example I want to store this JSON (that would be the first parameter in the function):
{
"name": "client.firstName",
"surname": "client.surname",
"age": "client.age",
"skills": [
{
"skillName": "client.skills[index].name",
"level": "client.skills[index].levelNumber",
"categories": [
{
"categoryName": "client.skills[index].categories[index].name",
"isImportant": "client.skills[index].categories[index].important"
}
]
}
]
}
And the second paramenter would be something like this (it's the object where you find the information.
{
"client": {
"firstName": "Jake",
"surname": "Long",
"age": 20,
"skills": [
{
"name": "Fly",
"level": 102,
"categories": [
{
"name": "air",
"important": true
},
{
"name": "superpower",
"important": false
}
]
},
{
"name": "FastSpeed",
"level": 163,
"categories": [
{
"name": "superpower",
"important": false
}
]
}
]
}
}
The idea it's: with de paths that I have in the first object, find it in the second one.. The problem I found it's when I have arrays, because when I defined the mapping rules I don't know how many positions will have the array I want to map. So in the mapping object (first) I'll only define the path but I'll not put it with the same lenght of the secondone because I don't know how much it will have.

get string of elements by name

I'm newbee in JS so i need your help.
I have this JSON code :
{
"data": {
"people": [
"get_my_obj": [
{
"yearcome": 2006,
"email": "email1#test.com",
"came": "1.12",
"name": "Alex "
},
{
"yearcome": 2010,
"email": "email2#test.com",
"came": "1.12",
"name": "John"
},
{
"yearcome": 2012,
"email": "email3#test.com",
"came": "1.12",
"name": "Max"
}
]
}
}
How i can get string of elements with emails?
For example var a = email1#test.com;email2#test.com;email3#test.com;
Thats really hard for me because if i have only 2 objects so string must show 2 emails if 3 objects show 3 emails.
Please help me find the way how to do it
var s = { data: ....};
var mails = s.data.people.get_my_obj.map(function (e) { return e.email; }).join(';');
console.log(mails);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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

Categories