Combine JSON Arrays in Javascript with - javascript

I am trying to learn/use Node and Javascript by re-coding a PHP/MYSQL application I made that is not very efficient - as I built it while I was trying to earn those technologies as well.
I am trying to re-use a some of the information that is created or stored in JSON format.
I have in one file a set of 52 questions that looks like such...
//questions.json
{
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
},
"Administration" : {
"Question 9": "Administration positively supports faculty in a professional manner.",
"Question 10": "Administration actively encourages a dialogue concerning school related issues.",
"Question 11": "Administration is actively engaged in developing/supporting/maintaining a clear school vision.",
"Question 12": "Administration makes sure that the financial stability and integrity of the school is well maintained.",
"Question 13": "Administration/Ownership uses school funds to support the well being of the school."
},...
I also have a Knex script that does a query on the data and returns an array like below....
[ { Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5,
Q9: 7.63,
Q10: 8.13,
Q11: 8.5,
Q12: 8.88,
Q13: 8.75,
Q14: 7.38,
Q15: 8.13,
Q16: 8.56,...
I would like to try to combine these two arrays to look like...
{
"School" : {
{"Question 1" : {
"Question" : "The facilities of the school adequately provide for a positive learning/working experience.",
"Average" : 8.44
},
{"Question 2" : {
"Question" : ""School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc."",
"Average" : 9.13
}
If need be I can remove the category divisions within the .json file if that make combining easier, but in the end applications I display the data in sections, so I will eventually filter it. I just thought maybe dividing it in the json file would make it easier.
I am able to concat the arrays, and I have looked at .map but I am not sure how I would apply it to this. It looks like I would need a nested loop?

Using a double forEach loop:
const questions = {
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
}
};
const scores = {
Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5
};
// Placeholder for your result
const result = {};
// Iterate through the question categories:
const categories = Object.keys(questions);
categories.forEach(cat => {
// Add category to result
result[cat] = {};
// Get the question keys for that category
const questionKeys = Object.keys(questions[cat]);
questionKeys.forEach(q => {
// Get the score key. i.e: Question 1 -> Q1
const scoreKey = q.replace('Question ', 'Q');
// Add question to result
result[cat][q] = {
Question: questions[cat][q],
Average: scores[scoreKey]
};
});
});
console.log(result);

What I do below is basically:
I take the question number out of "Question 1"
Combine it with "Q" to get "Q1"
And then the plain old key lookup in the object you have based on this new string.
All this, in loops below
var newObj = {};
// replace /*questions.json*/ with your actual object.
for (var category in /*questions.json*/){
var questionsObj = /*questions.json*/[category];
newObj[category] = {}
for (var question in questionsObj) {
newObj[category][question] = {};
newObj[category][question].question = questionsObj[question];
var qNumber = question.split("Question ")[1];
newObj[category][question].Average = dataArray[0]["Q"+qNumber];
}
}

Related

Is it possible to get a list of all items in an array of objects that match items in another array?

I'm working on a React project that'll allow me to search through a list of games to help me decide what to play based on what I'm in the mood for, currently I can add games to a JSON file but I'm really struggling with the searching part.
Right now, to add a new game, you'll enter the title, genre(s) and a description of the game. The genre field is a ReduxForm FieldArray object, and I think that's what's giving me the trouble. Here's my current JSON file
{
"games": [
{
"name": "Rainbow Six: Siege",
"genres": [
{
"genre": "tactical"
},
{
"genre": "shooter"
}
],
"description": "tactical team based shooter",
"id": 1
},
{
"name": "Resident Evil 2",
"genres": [
{
"genre": "horror"
},
{
"genre": "survival"
},
{
"genre": "shooter"
}
],
"description": "classic resident evil 2 remake in 2019",
"id": 2
},
{
"name": "Rocket League",
"genres": [
{
"genre": "cars"
},
{
"genre": "competition"
},
{
"genre": "one more game"
}
],
"description": "soccar!",
"id": 3
}
]
}
This is the dummy data I'm using to search:
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = [];
Once I get the search working with this data, the plan is to allow me to just type in data on the frontend in one textbox, so "horror, shooter" would be my search term. The result from this search should only return Resident Evil 2, however I'm also receiving Rainbow Six: Siege as a result, even though it's missing one of my requested genres.
searchedList.forEach(searchedGenre => {
this.props.games.map(game => {
if (
game.genres.find(
({ genre }) =>
genre.toLowerCase() ===
searchedGenre.toLowerCase().trim()
) !== undefined
) {
foundGames.push(game);
}
});
});
I understand why I'm getting both Rainbow Six and Resident Evil as a result, because I'm not actually checking that both genres are in the games genres when I add the game to the foundGames array, but I'm completely lost on how I'd go about making sure all of the genres are in a game before I add it.
This would be a bit easier if your genres was a simple array of strings rather than objects, but still you can check pretty succinctly by leveraging some() and every() within filter() (btw filter() is a better choice than map() + push() here)
let games = [{"name": "Rainbow Six: Siege","genres": [{"genre": "tactical"},{"genre": "shooter"}],"description": "tactical team based shooter","id": 1},{"name": "Resident Evil 2","genres": [{"genre": "horror"},{"genre": "survival"},{"genre": "shooter"}],"description": "classic resident evil 2 remake in 2019","id": 2},{"name": "Rocket League","genres": [{"genre": "cars"},{"genre": "competition"},{"genre": "one more game"}],"description": "soccar!","id": 3}]
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = games.filter(game => searchedList.every(searchItem => game.genres.some(g => g.genre == searchItem) ))
console.log(foundGame)
The filter condition basically says you want every game in searchedList to match at least one genre in the game. This will make it only return games that match every genre.

Map local .json data in React

I have a local .json file formated below
{
"results": [
{
"id": 1,
"title": "2 bedroom apartment to rent",
"location": "30 South Colonnade London E14 5EZ",
"description": "The building offers a communal lifestyle which consists of a large lounge area with dining room, working space, TV lounge, gym, stylish meeting rooms, free table tennis, free WIFI and a spacious communal roof terrace. Local transport includes Canning Town DLR and Jubilee Line (0.1 miles). Argo Apartments is managed by Grainger plc, one of the UK's leading professional landlords with over 100 years experience.",
"price": "1,800",
"beds": 2,
"bathrooms": 1,
"landlord": "Hamptons International Lettings",
"images": ["image1", "image2"]
},
{
"id": 2,
"title": "2 bedroom flat to rent",
"location": "Textile Building, Chatham Place, Hackney, London, E9",
"description": "SHORT LET - Forming part of the new eagerly awaited Textile Building in Hackney Central E8, this stunning two double bedroom property has been finished to the highest standard, featuring two modern fitted bathrooms (one en-suite), two equal double bedrooms, spacious open plan reception with brand new integrated kitchen, exposed brickwork and communal underground bike storage.",
"price": "2,400",
"beds": 2,
"bathrooms": 1,
"landlord": "Stirling Ackroyd, Hackney",
"images": ["image1", "image2"]
},
{
"id": 3,
"title": "3 bedroom apartment to rent",
"location": "Sixth Floor Tower Building 11 York Road London SE1 7NX",
"description": "A fantastic three bedroom apartment set in this popular development close to Vauxhall and Stockwell tube stations. The apartment is neutrally decorated throughout and is available either furnished or unfurnished. Residents will enjoy the plethora of shops, bars and restaurants and leisure activities in this popular part of London as well as the excellent commuter links towards Central London.",
"price": "2,050",
"beds": 3,
"bathrooms": 2,
"landlord": "Regent Letting and Property Management",
"images": ["image1", "image2"]
}
],
"newResults" : [
{
"id": 4,
"title": "2 bedroom flat to rent",
"location": "Conway Street, Fitzrovia, W1T",
"description": "Complete is delighted to market this newly renovated period property situated on the corner of Fitzroy Square in the heart of Fitzrovia, W1. The property is located on the ground floor and comes with 2 double bedrooms, shower room, open plan living and kitchen area. The kitchen is fully fitted with Siemens appliances and Duravit fittings in the bathroom. This apartment has high ceiling and retains its original period features. Located on the corner of this garden square this development was built in the 18th Century and benefits from being in the heart of vibrant London whilst also being a quiet residential area.",
"price": "1,500",
"beds": 2,
"bathrooms": 1,
"landlord": "Barnard Marcus Lettings",
"images": ["image1", "image2"]
}
]
}
I want to be able to call the relevent information mapped to a component as below
class ResultsLists extends React.Component {
constructor(props) {
super(props)
this.state = {
results: resultsData
}
}
render() {
const results = this.state.results.results.map((result) =>
<li>{result}</li>
);
return (
<div className="rst-List">
<ul className="rst-List_Items">
{results}
</ul>
</div>
)
}
}
I can't seem to get it too work and am getting the error - Objects are not valid as a React child. There seems to be a varying variety as to why this isn't working, wondered whether someone could sanity check.
You're mapping over the results, but then you're putting the whole result object into the JSX.
This is an example of how to map over data:
const someData = [{ name: "Colin" }, { name: "Ricardo" }];
const App = () => {
const temp = someData.map(o => <li>{o.name}</li>);
return (
<div>
<ul>{temp}</ul>
</div>
);
};
Note that we have {o.name} and not just {o}.
Working example here.
So in your case, you need something like:
const results = this.state.results.results.map((result) =>
<li>{result.title}</li>
);

Looping through object and inputing into certain indexes using jQuery

I am looking to loop through an object and input into certain indexes using jQuery. I am using Sweet Alert 2 and the chaining modals but I need to generate the titles dynamically. The titles are in the array below.
The object used by SA2 is the following:
var steps = [{
title: 'Questions',
input: 'radio',
inputOptions: inputOptions,
}]
I guess 'each' of some kind after the squared bracket.
["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
Essentailly I need to create:
var steps = [{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
},
{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
}]
Thank you for any help
You can use Array.map()
es6
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(e => ({title:e,input:"radio",inputOptions:{}}));
console.log(result)
es5
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(function(e){
return {title:e,input:"radio",inputOptions:{}};
});
console.log(result)
You need a template object:
var step = {
title : '',
input : 'radio',
inputOptions : inputOptions
};
Then you will just iterate through the array:
var titles = [
"Washing Machine diagnosis",
"Washing Machine type",
...
"Do you have a receipt?"
];
var steps = titles.map((title) => {
var clone = Object.assign({}, step);
clone.title = title;
return clone;
});
or just use Underscore.js to clone objects if you do not like assign()
How about this
$.each(steps, function(i, step){
step.title = myArray[i];
});
This uses JQuery to loop through the array.
I'm not sure i've understand your question but how about this
const titles = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
const steps = titles.map((title) => {
return {
title,
input: 'radio',
inputOptions
}
})

best practice data design in firebase

How could i structure data for following scenario?
There is an app called Food Ordering System. It contains
Username(Who is registering this restaurant menus for online order)
Restaurant_name
Description
Location
Estimated Delivery
Menu(Has multiple menus for one restaurant)
My design
"restaurant":{
"username":{
"restaurant_name":"KFC Restaurant",
"description":"short description on restaurant",
"estimated delivery":"1hour/km",
"distance":"20km away",
"location":"Kathmandu",
"rating":"rating star up to 5",
"menus":{
"menu":{
"item":"buff momo",
"price":"$5",
"rating":"rating star up to 5"
},
"menu":{
"item":"Fried Chicken",
"price":"$10",
"rating":"rating star up to 5"
},
"menu":{
"item":"BBQ",
"price":"$20",
"rating":"rating star up to 5"
}
}
}
}
Is my design the best practice design?
It actually depends on what you want to do with this data.
If in your website you want to show a list of all restaurant and when you click on restaurant show the list of menu they are offering, storing the menu inside the restaurant might not be a good idea.
Because according to the doc :
When we read a data node in our Firebase database, we also retrieve all of its children!
(the old one) https://www.firebase.com/docs/rest/guide/structuring-data.html#section-denormalizing-data
Also, imagine if you want to do a search bar and look for a menu (like chicken nuggets) and return the list of restaurant offering this I would design your database this way:
"restaurant":{
"$username":{
"restaurant_name":"KFC Restaurant",
"description":"short description on restaurant",
"estimated delivery":"1hour/km",
"distance":"20km away",
"location":"Kathmandu",
"rating":"rating star up to 5",
...
}
}
"menus":{
"$username" : {
"menu":{
"item":"buff momo",
"price":"$5",
"rating":"rating star up to 5"
},
"menu":{
"item":"Fried Chicken",
"price":"$10",
"rating":"rating star up to 5"
},
"menu":{
"item":"BBQ",
"price":"$20",
"rating":"rating star up to 5"
}
}
}

How to find matching datas from two json documents in couchdb?

How to find matching datas from two json documents.For ex: I have two json documents and skills json documents.
In Skills Document:
{
"_id": "b013dcf12d1f7d333467b1447a00013a",
"_rev": "3-e54ad6a14046f809e6da872294939f12",
"core_skills": [
{
"core_skill_code": "SA1",
"core_skill_desc": "communicate with others in writing"
},
{
"core_skill_code": "SA2",
"core_skill_desc": "complete accurate well written work with attention to detail"
},
{
"core_skill_code": "SA3",
"core_skill_desc": "follow guidelines/procedures/rules and service level agreements"
},
{
"core_skill_code": "SA4",
"core_skill_desc": "ask for clarification and advice from others"
}
]}
In Employee Document:
{
"_id": "b013dcf12d1f7d333467b12350007op",
"_rev": "3-e54ad6a14046f809e6da156794939f12",
"employee_name" :"Ashwin",
"employee_role" : "Software engineer",
"core_skills":["SA1","SA4"]
}
I have no idea what you want to do, but the following might be helpful. Assuming that the first data set is a list of skills and their descriptions and the second is an employee record, then assigning to variables with suitable names might look like:
var skillCodes = {
"_id": "b013dcf12d1f7d333467b1447a00013a",
"_rev": "3-e54ad6a14046f809e6da872294939f12",
"core_skills": [{
"core_skill_code": "SA1",
"core_skill_desc": "communicate with others in writing"
},{
"core_skill_code": "SA2",
"core_skill_desc": "complete accurate well written work with attention to detail"
},{
"core_skill_code": "SA3",
"core_skill_desc": "follow guidelines/procedures/rules and service level agreements"
},{
"core_skill_code": "SA4",
"core_skill_desc": "ask for clarification and advice from others"
}
]};
var employee0 = {
"_id": "b013dcf12d1f7d333467b12350007op",
"_rev": "3-e54ad6a14046f809e6da156794939f12",
"employee_name" :"Ashwin",
"employee_role" : "Software engineer",
"core_skills":["SA1","SA4"]
};
Creating a skills index makes looking for particular skills much simpler, some code to do that is:
var skillCodeIndex = {};
skillCodes.core_skills.forEach(function(item){
skillCodeIndex[item.core_skill_code] = item.core_skill_desc;
});
Now all that is required is a function to get the skills for a particular employee, say:
function getCoreSkills (employee) {
console.log('Employee ' + employee.employee_name + ' has the following core skills:');
employee.core_skills.forEach(function(skill) {
console.log(skill + ': ' + skillCodeIndex[skill]);
});
}
An example:
getCoreSkills(employee0);
Employee Ashwin has the following core skills:
SA1: communicate with others in writing
SA4: ask for clarification and advice from others
The above could become much more OO given constructors for skillCodes and employee instances, I'll leave that to you.

Categories

Resources