Parsting tree with getJson - javascript

I have a JSON file with order data. The JSON file is formatted like this:
{
"orders": [
{"name": "Peter", "email": "peter#aol.com"}
{"name": "David", "email": "david#aol.com"}
{ "name": "George", "email": "george#aol.com"}
]
}
As you can see; all the data is part of a branch called "orders" and then each order is its own branch, but the branch doesn't have a name.
I am trying to generate a list of the "name"s in the dataset.
With a simplified dataset, I would do something like:
$(data).each(function(i, name){
$('#namesText').append($("li")
.append($("li").append(name.name))
});
})
This however doesn't work as the data is not in the first level of the tree.
My question is, how do I go down levels when the levels don't have a name?

This sounds like a DFS problem where each object has keys that can possibly be a primitive data type or another object. Since the name field could be at any level in this given constraint you need to solve for, I would say use DFS algo where it traverses each key in the object and if there is another object, look into that until you find a name field. Better solution is to redesign the data structure so that you are guaranteed to know which level and location the name field is at any time.

If you want a list of the name property from the elements of the orders array you could use Array.map:
const names = myJson.orders.map(o => o.name);

Try
namesText.innerHTML= data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``
var data = {
"orders": [
{
"name": "Peter",
"email": "peter#aol.com",
},
{
"name": "David",
"email": "david#aol.com",
},
{
"name": "George",
"email": "george#aol.com",
}
]
}
namesText.innerHTML= data.orders.map(p=>`<li>${escape(p.name)}</li>`).join``
<ul id="namesText"></ul>

Related

map a 3 nested array javascript

const aboutMe = [{
"name": "frank",
"about": [{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": [{
"first": "desert",
"last": "noodles"
}]
},
{
"mood": "happy",
"dinner": []
}
]
}]
const AllBreak = aboutMe.about.map((dinner) => ((dinner.first, dinner.last)));
const expectedOutput =["first": "desert", "last": "noodles", "first": "desert", "last": "noodles"]
console.log(aboutMe, AllBreak, expectedOutput)
so am trying to filter through a nested array learning from a tutorial I don't know why it returns cannot read property of map why is that pretty sure i filtered correctly according to the tutorial
Firstly, aboutMe is an array with an object that has an about property in it. So, if you want to access this property, you need to first access the first element of the array and then access the about property in it.
Secondly, (dinner.first, dinner.second) doesn't actually make any sense here.
Because when you have multiple expressions separated by commas in a bracket, each of those expressions get evaluated but only the last one is returned. So, here returning (dinner.first, dinner.second) is equivalent to returning dinner.second.
So, if you only want dinner.second then just return that or put them in an array (or object) and return that.
Also, since in your example it seems that it is not guaranteed that the dinner array would always have an object inside it, it is best to use Optional Chaining here.
Please have look at the solution below:
const
aboutMe = [{name:"frank",about:[{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[{first:"desert",last:"noodles"}]},{mood:"happy",dinner:[]}]}],
res = aboutMe[0].about.map(({dinner}) => [dinner?.[0]?.first, dinner?.[0]?.last])
console.log(res);
aboutMe is an array, if you want to get the property of the first element, you can use indexing [0]
const AllBreak = aboutMe[0].about.map(() => ...);

Javascript for of loop errors

this is the file I'm using
[
{
"id": 1,
"name": {
"first": "Paige",
"last": "Bools"
},
"birthDate": "1995-02-04T07:34:45Z",
"contact": {
"phone": "8989068955",
"email": "pbools0#webmd.com"
},
"address": {
"street": "476 Veith Parkway",
"city": "Cuamba",
"country": "Mozambique"
},
"accessCount": 776,
"isManager": false
},
{
"id": 2,
// rest of json
}
]
Bunch of users all there.
My requirement is like this:
use a for-loop to iterate over the items in users
concatenate the first name and last name and assign to a name variable
call console.log() with the name variable
The function doesn't need to return anything.
I wrote my function like this. But its not working
function formatNames() {
for (name of users)
var name = users.name.first + users.name.last;
console.log(name);
}
formatNames();
Do u guys see any problem in this function?
The users array doesn’t have a name property, so users.name.first and users.name.last aren’t going to work.
The for loop is iterating the items in the array, not the names in the array. You can call the variable “name” if you want, but that’s not what it represents and will cause confusion.
Each time through the loop your name variable represents a user. So (leaving the loop variable named “name”) you’d need: name.name.first.
If you rename the loop variable to “user” it will make more sense:
for (const user of users) {
// do stuff with user.name.first
}

Can a JSON array contain objects of different key/value pairs?

Can a JSON array contain Objects of different key/value pairs. From this tutorial, the example given for JSON array consists of Objects of the same key/value pair:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
If I want to change it to have different key/value pairs inside the JSON array, is the following still a valid JSON?
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
Just want to confirm this. If so, how can I use JavaScript to know if the JSON "example" field contains the first homogeneous objects or the second heterogeneous objects?
You can use any structure you like. JSON is not schema based in the way XML is often used and Javascript is not statically typed.
you can convert your JSON to a JS object using JSON.parse and then just test the existence of the property
var obj = JSON.parse(jsonString);
if(typeof obj.example[0].firstName != "undefined") {
//do something
}
It doesn't matter you can mix and match as much as you want.
You could just test it
typeof someItem.example !== 'undefined' // True if `example` is defined.
It's perfectly valid JSON. Personally I prefer this syntax better, because it reads easier:
{
"example": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"fruit": "apple"
},
{
"length": 100,
"width": 60,
"height": 30
}
]
}
As to answer your second question, you can read data from a JSON string by using var data = JSON.parse(datastring);. Then simply use it by calling data.property.secondlevel. Any variable can be an object, array, string or number, allowing for nested structures.
You are free to do what you want with the contents of the array. Jus remember about this before you try to iterate an access properties of each item in your array.
one thing: you won't be able to deserialize this to anything else than an array of object in your server side, so don't have surprises later.
as a hint, maybe you could include a common field in the objects specifying the "type" so later is easy to process.
var array = [{"type":"fruit", "color":"red"},
{"type":"dog", "name":"Harry"}];
var parser = {
fruit:function(f){
console.log("fruit:" + f.color);
},
dog: function(d){
console.log("dog:"+d.name);
}};
for(var i=0;i<array.length;i++){
parser[array[i].type](array[i]);
}

How to search and select an object in JSON

Consider a JSON like this:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
},
{
"type": "something_else",
"where": "NY"
}]
I want to search in the JSON value with a key (for example type='person') and then select a whole object of matched item in JSON. For example when I search for type='person' I expect this value:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
}]
Because it's a really big JSON value, I don't want to do a brute-force search in all nodes, so I think the only way is using Regular Expressions but I don't know how can I write a Regex to match something like above.
I'm using NodeJs for the application.
Using underscore.js#where:
var results = _(yourObject).where({ type: 'person' })
If your data set is very very big [e.g. 10k or so], consider filtering / paginating stuff server side.
Plain javascript :
var results = dataset.filter(function(p) {
if(p.type == 'person')
return true;
});
If the requirement is to scan multiple times through the collection, the following one time construction overhead might be of worth.
Use hashing based on values of type.Convert the current data structure to hash map.
var hashMap ={
};
hashMap['person'] =[{},{}];
Hope this helps you.
Use
$.grep(jsonarrayobj,function(n, i){
if(n.type==="person")
{}
})

How to create Backbone collection from following json array?

I am getting a following JSON(/users.json) which contains users:
[
[
{ "id": "43343", "project_id": "1", "username": "Amy" }
{ "id": "34244", "project_id": "1", "username": "Tommy" }
],
[
{ "id": "76575", "project_id": "2", "username": "Izzy" }
{ "id": "13322", "project_id": "2", "username": "Sam" }
],
{ "id": "09983", "project_id": "3", "username": "Max" }
]
When project has one user I get one user hash which is not in array.
I would like to build a Backbone collection with all users. How to do that?
You provide an array of arrays of users. So to fetch all users in the init method, you can give it data but as an array of users, i.e. you will flatten this original array of arrays once with underscore flatten method :
data = _(data).flatten(true);
Then the collection constructor will natively understand your json array.
But maybe you already do this transformation in the fetching method and this is not the problem you are facing..
If you have defined a collection (say userCollection) with a user model you should be able to simply do something like this:
var col;
$.getJSON("/users.json", function(data) {
col = new userCollection(data);
});
This would more likely be done in the fetch function of the collection, but the principle here is that you can pass an array of objects to a collection and it will marshal all from json to backbone models.

Categories

Resources