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
}
Related
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(() => ...);
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>
I would like to be able to type in "Hammerhead" to call the "Hammerhead Shark" object without its full name. Is this possible and if so how?
I tried using array.indexOf(string) though it doesn't really seem to help since it requires an exact match such as typing "Hammerhead Shark"
JS:
const JSON = require('animals.json');
var animals = Object.keys(JSON);
if (animals.indexOf("Hammerhead")) {
console.log(JSON["Hammerhead"].name);
}
JSON:
{
"Hammerhead Shark": {
"name": "Shark",
"age": "300"
},
"Duck": {
"name": "Duck",
"age": "1000"
}
}
I expect the output to be "Shark" instead of undefined.
It seems you want to get access the value in object. By its partial name.
Get the entries of object using Object.entries()
Find the key which includes() the given partial key.
return the second element of the found entry.
const obj = { "Hammerhead Shark": { "name": "Shark", "age": "300" }, "Duck": { "name": "Duck", "age": "1000" } }
function getValueByPartialKey(obj,key){
return (Object.entries(obj).find(([k,v]) => k.includes(key)) || [])[1]
}
console.log(getValueByPartialKey(obj,"Hammerhead"))
You can use string.includes(word) to return the name that matches the string that you're searching for, along with Array.filter iterates over the values too, and returns the result(s) you want.
I have several objects like this and wonder how I can search between these, say that we got the number 1 and want to figure out what the name is.
Should I loop it or what do you guys suggest?
To make things clear, I do want to get the other objects by using the number. Is it possible?
{
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
}
You could use a map and use the room number as identifier. This way you can access the room data via the room number like that:
var data = {
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
};
// or load it from a file:
// var data = require('./data.json');
var rooms = new Map();
for(room of data.room) {
rooms.set(Number(room.number), room);
}
// access data for room with number 1
alert(rooms.get(1).name);
Firstly, bring in the file. Make sure to include the './' before the file name to show that it's from the current directory.
const data = require('./data.json');
Now the JSON data is stored inside the variable data. To access the members, use the dot operator. data.room will return the array of rooms.
To access the individual room, use data.room[i] where i is the numbered element in the array (starting from 0). For example, to access the first room:
const first_room = data.room[0];
This first_room variable can now be used to access the name.
console.log(first_room.name);
This will log "room1" to the console.
You can try this. This will help you.
var roomData = {
"room": [
{
"number": "1",
"name": "room1"
},
{
"number": "2",
"name": "room2"
}
]
}
for(key in roomData.room){
console.log("Room Number - " + roomData.room[key].number);
console.log("Room Name - " + roomData.room[key].name);
}
This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck