Search in json file with Node JS - javascript

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);
}

Related

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
}

Loop into Array of Objects comparing two arrays - PUG (Jade)

I am trying in Javascript, using PUG template (if possible), to compare two arrays and when I find a correspondance in IDs, display some particular elements.
// First Array : I iterate over "hearts" object
// Called in PUG : - const user
[
{
"hearts": [
"5e70c63a94b27b164c9b897f",
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bb1189978fd5afc98c57a",
"email": "catherine#catherine.com",
"name": "Catherine",
"photo": "0121b7fe-b2ae-4e75-979d-7dea1a432855.jpeg",
"__v": 0
},
{
"hearts": [
"5e723c75e4bfdf4f58c55e32"
],
"_id": "5e6bc41f5915e3d2980a5174",
"email": "marc#marc.com",
"name": "Marc",
"photo": "4caa7bfb-6408-4893-a78b-fa6e8e5b03e7.png",
"__v": 0
}
]
// Second array : I iterate over "author.hearts" object
// Called in PUG : - const store
[{
"product": {
"categories": [
1,
2
]
},
"_id": "5e6bcc76c4022eae00e22af6",
"date": "2222-02-20T21:22:00.000Z",
"author": {
"hearts": [
"5e723c75e4bfdf4f58c55e32",
"5e70c63a94b27b164c9b897f"
],
"_id": "5e6bb1189978fd5afc98c57a",
"__v": 0
},
"created": "2020-03-13T18:09:58.086Z",
"id": "5e6bcc76c4022eae00e22af6"
}]
I want to loop over the first array, find the first ID (here 5e70c63a94b27b164c9b897f), loop over the second array and see if this ID is present within the "author.hearts" object. If it is not, carry on with the second ID and if it is present, display all the keys (tags, photos, _id, date...) from the object where the ID was found.
In my example, I have just one object in my array, but I'll be having much more later on.
Many thanks for your help
If I'm understanding correctly you can do something like this. Loop through all your users and when you find their id in author.hearts stop the loop there and return the object the user's _id was found in.
var resultFound = undefined;
try {
user.forEach((el) => {
const id = el._id;
const result = store.find(el => el.author.hearts.includes(id));
if (result) {
resultFound = result;
throw resultFound;
}
});
} catch (e) {
if (e !== resultFound) {
throw e;
}
}

Retrive array object from object in Javascript

var obj={"firstName":"John","lastName":"Smith","isAlive":true,"age":25,"address":{"streetAddress":"21 2nd Street","city":"New York","state":"NY","postalCode":"10021-3100"},"phoneNumbers":[{"type":"home","number":"212 555-1234"},{"type":"office","number":"646 555-4567"},{"type":"mobile","number":"123 456-7890"}],"children":[],"spouse":null};
I want to access the phoneNumbers field
So I use
phone=obj.phoneNumbers;
I get an array but without "phoneNumbers" field.I want to get someting like this:
{
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
]
}
You have to create a new object then
var phone = { "phoneNumbers": obj.phoneNumbers };
You can add that part in:
var phone = {"phoneNumbers" : obj.phoneNumbers};
Although there should be a good reason for doing this (like, need to pass it to an API that expects exactly "x"). A single-property object is about as useful as the value of its single property.
How about making a function and using it for other similar purposes:
function transform (prop, payload) {
return { [prop]: payload };
}
And use it like:
phone = transform('phoneNumbers', obj.phoneNumbers);

Simplify an associative array

I'm hitting an api built using CakePHP. Cake returns its objects like this:
[
{
"Note": {
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
}
},
{
"Note": {
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
}
]
What I want to do is take that result and basically get rid of the keys. Something like this:
[
{
"id": "1",
"clas": "test",
"obj_id": null,
"note": "test"
},
{
"id": "2",
"clas": "another",
"obj_id": null,
"note": "another"
}
]
I'm basically just trying to make it easier to reference this in Angular. I need to do this on the client side. Any ideas?
You could refactor it like so:
var json = '[{"Note":{"id":"1","clas":"test","obj_id":null,"note":"test"}},{"Note":{"id":"2","clas":"another","obj_id":null,"note":"another"}}]';
var obj = JSON.parse(json);
var arr = [];
for (i = 0; i < obj.length; i++)
{
arr.push(obj[i].Note);
}
Working example here
(Note also that if your key value 'Note' isn't always the same, this will change dramatically. It's likely that 'Note' isn't going to be the same in each instance either; that would generate an improperly keyed object. Alternatively, if you always need the first object in the array, you could use obj[i][0] instead).
(More note if you're using cakephp, this would be much easier done using Hash::, but if you need to do it client side, this is the solution).

Complex JSON string Parsing in JavaScript

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

Categories

Resources