I'm currently learning Node.js, at the moment I have a JSON file (called cars.json) which is as follows:
[
{
"id": 1,
"brand": "BMW",
"bookedUntil": null
},
{
"id": 2,
"brand": "Mercedes",
"bookedUntil": null
},
{
"id": 3,
"brand": "Golf",
"bookedUntil": null
},
{
"id": 4,
"brand": "Holden",
"bookedUntil": null
},
{
"id": 5,
"brand": "Subaru",
"bookedUntil": null
}
]
I have a PUT method which gets passed an ID value, this ID value is associated with an item inside the JSON object.
The method is as follows:
const data = require('./public/cars.json'); // JSON FILE
app.put('/booking/:id', (req, res) => {
data.forEach((car) => {
if (car.id == req.params.id) {
var date = new Date();
date.setDate(date.getDate() + 1);
car.bookedUntil = date;
}
})
fs.writeFile('./public/cars.json', JSON.stringify(data, null, 2), (error) => {
if (error) {
} else {
res.send('Booking has been made');
}
});
});
All I am doing is finding the record that matches the ID, updating the bookedUntil field with a date in the future i.e one day then re-writing the file back to disk.
Now this is working as expected, however I'm curious to find out if I can just update one item without having to loop and re-write the whole file again?
Related
Actually I'm trying to get all the value of object1 and get true if Like object has some id that match with current user id
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like": Object {
"-MgpHytKWNplejaxtLLF": "-MgpHytKWNplejaxtLLF",
},
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like": Object {
"-MgFbI5wXjtjKln1Wkqe": "aC9dL88GCAXdnGyefY1XDiXd7Iu1",
},
"likes_count": 0,
},
]
Here is my code, arr contains whole object that are given above
const us = arr.map((item) => {
return item.like;
});
const ik = us.includes(uid);
console.log("snap ", ik);
I want given below object that include like variable true if like object have user id otherwise it assign false
Array [
Object {
"id": "-MgFbI5wXjtjKln1Wkqe",
"like":false,
"likes_count": 7,
},
Object {
"id": "-MgpHytKWNplejaxtLLF",
"like":true,
"likes_count": 0,
},
]
const us =Array(); // us is the final table that you need
for(i=0;i<arr.length;i++){
us[i]= {
"id":arr[i].id,
"like": arr[i].like===uid?true:false,
"likes_count": arr[i].likes_count,
}
}
or this :
const us = Array();// us is the final table that you need
arr.forEach((element,index) => us[index] = {
"id":arr[index].id,
"like": arr[index].like===uid?true:false,
"likes_count": arr[index].likes_count,} );
Im trying to take JSON data and pass it into my 'HistoryChart' Component to try and map the dates and prices into two arrays so that I can present them on my chart. However, I keep getting undefined errors.
Here is the JSON Data:
{
"_id": 1,
"name": "",
"brand": "",
"image": "",
"sources": [],
"history": [
{
"_id": 3,
"price": "299.99",
"product": 1,
"date": "2021-07-01"
},
{
"_id": 4,
"price": "399.99",
"product": 1,
"date": "2021-07-08"
},
{
"_id": 5,
"price": "499.99",
"product": 1,
"date": "2021-07-15"
},
{
"_id": 6,
"price": "599.99",
"product": 1,
"date": "2021-07-22"
},
{
"_id": 7,
"price": "699.99",
"product": 1,
"date": "2021-07-29"
}
]
}
Here is my HistoryChart Component:
function HistoryChart({product}) {
var dates = product.history.map(function(e){ //<-- The Problem lies here where it says cannot map undefined.
return e.date;
});
var prices = product.history.map(function(e){
return e.price;
});
return (
<div>
<Line
data={{
labels: dates,
datasets: [{
label: `Average Price History (ID: ${product._id})`, //<-- This part works
backgroundColor:/* 'transparent' */ '#00ad0e',
borderColor: '#00ad0e',
data: prices,
}]
}}
width={100}
height={50}
options={{ maintainAspectRatio: true }}
/>
</div>
)
}
I am also using redux to get the Data:
const productDetails = useSelector(state => state.productDetails)
const {error, loading, product} = productDetails
And the data is passed into the HistoryChart Component like this:
<HistoryChart product={product}/>
Any Help would be Much appreciated, Thanks.
Sorry if this is not your principal problem, but same time when .map resulting in undefined the most simple adjust is verify if your array is undefined.
So in my projects i always check first if array is undefined, i will use your code to do a example
function HistoryChart({product}) {
if (product !== undefined){
var dates = product.history.map(function(e){
return e.date;
});
var prices = product.history.map(function(e){
return e.price;
});
}
Try this aproach and let me know if this work.
Cause of Error
As the data come from server, it take some time to load. and you get the undefine error because 1st time you want to access history of object product which is not yet loaded successfully.
Solution
const price = product && product.history.map(//do what you want)
use key values of object this way not cause any error because if product is not loaded it does'nt call map function and when product object loaded successfully it will call map function
So, I have a json which looks a little bit like this:
{
"data": {
"user": {
"edge_followed_by": {
"count": 22,
"page_info": {
"has_next_page": true,
"end_cursor": "Base64"
},
"edges": [
{
"node": {
"id": "id",
"username": "Username",
"full_name": "played",
"profile_pic_url": "URL"
}
}
]
}
}
}
}
And I want to filter out the username. How do I do that?
You could retrieve it with a map function there
const dataSample = {
"data": {
"user": {
"edge_followed_by": {
"count": 22,
"page_info": {
"has_next_page": true,
"end_cursor": "Base64"
},
"edges": [
{
"node": {
"id": "id",
"username": "Username",
"full_name": "played",
"profile_pic_url": "URL"
}
}
]
}
}
}
}
const getUsernames = data => {
return data.data.user.edge_followed_by.edges.map(e => e.node.username)
}
console.log(getUsernames(dataSample))
:)
This can be a little tricky to understand from the question first of all.
My interpretation of this is you want to extract a username
"Filtering" also could mean you want to remove something from a collection that passes a condition (or test) of some kind.
For example: Removing all even numbers from an array
let x = [1, 2, 4, 5, 6];
let filtered = x.filter(value => value % 2 === 0);
Now, I've looked at your json, and I think the best point of targeting this is by getting the "edges" property and running it through an inbuilt function like map; that could be used to get usernames. The edges is an array as well.
data.user.edge_followed_by.edges.map(userObject => userObject.username)
That would effectively remove all usernames from the edges if your tech stack of choice was javascript.
I got this info from a post like: https://coderin90.com/blog/2019/map-js
I am using the node.js package xml2js to transform xml into json.
Documentation is here: https://www.npmjs.com/package/xml2js
My problem is that attributes for those xml are not correctly transformed.
example XML with multiple events
<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5">
Result from JSON.stringify(result.search.events)
The event tag is only once in the generated JSON - My expectation is that it should have multiple tags event. So I assume the transformation process went wrong. I tried multiple options for the parser like ignoreAttrs, explicitArray or explicitChildren but without success.
[{
"event": [{
"$": {
"id": "E0-001-098932239-8"
},
]
}, {
"$": {
"id": "E0-001-105389601-2"
},
}, {
"$": {
"id": "E0-001-104342965-3"
},
}, {
"$": {
"id": "E0-001-104830349-3"
},
access JSON elements
After correct transformation I expect to simply access the JSON elements via event[1].$.id
but all tries are unsuccessful:
events.event --> undefined
events.event.$ --> undefined
events.$ --> undefined
My Question is now: how can i correctly transform the xml into JSON and access the elements correctly?
Javascript is starting from 0, you should get events[0].event[0].$.id
Also, you can try with another package (camaro) with simply and easily change the desired result.
Example:
const xml = '<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5"></event></events>'
const temp = {
events: ['/events/event', {
id: '#id'
}]
}
const transform = require('camaro')
const results = transform(xml, temp)
console.log(JSON.stringify(results, null, 2))
Results
{
"events": [
{
"id": "E0-001-098932239-8"
},
{
"id": "E0-001-105389601-2"
},
{
"id": "E0-001-104342965-3"
},
{
"id": "E0-001-104830349-3"
},
{
"id": "E0-001-105374979-6"
},
{
"id": "E0-001-105389620-7"
},
{
"id": "E0-001-104247759-2"
},
{
"id": "E0-001-104342949-5"
}
]
}
I need help pushing the values from a filtered json, I need this generate a nested ul list, I can not modify the json format at this point, I you check the console.log you will see the values to create the list, at this point I can't figure how to complete the 'for loop' to render the html markup needed, any help will be appreciated, this is the jsfiddle http://jsfiddle.net/43jh9hzz/, and if you check the console log you will see the values.
This is the Js:
var json='';
var property_set = new Set();
function iterate(obj, stack) {
json="<ul>";
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
}
else {
// console.log(property);
property_set.add(property);
json+="<li>";
if(typeof obj[property] !== "number") {
json+="<li>"+obj[property]+"</li>";
console.log(obj[property]);
}
}
} json += "</li>";
}
}
var listEl = document.getElementById('output');
iterate(jsonObj)
And this is the json format:
var jsonObj =
{
"level_1": [
{
"level_1_name": "CiscoSingaporeEBC",
"level_2": [
{
"level_2_name": "Khoo Tech Puat",
"level_2_id": 2222,
"level_3": [
{
"name": "Boon Leong Ong",
"id": 6919
},
{
"name": "Kiat Ho",
"id": 6917
},
{
"name": "Overall Experience",
"id": 6918
}
]
}
]
},
{
"level_1_name": "CiscoLondonEBC",
"level_2": [
{
"level_2_name": "Bernard Mathews Ltd.",
"level_2_id": 2367,
"level_3": [
{
"name": "Barry Pascolutti",
"id": 7193
},
{
"name": "Kathrine Eilersten",
"id": 7194
},
{
"name": "Martin Rowley",
"id": 7189
}
]
},
{
"level_2_name": "FNHW Day 1",
"level_2_id": 5678,
"level_3": [
{
"name": "Jurgen Gosch",
"id": 7834
},
{
"name": "Overall Experience",
"id": 7835
}
]
},
{
"level_2_name": "Groupe Steria Day 1",
"level_2_id": 2789,
"level_3": [
{
"name": "Adam Philpott",
"id": 7919
},
{
"name": "Pranav Kumar",
"id": 7921
},
{
"name": "Steve Simlo",
"id": 7928
}
]
}
]
}
]
};
enter code here
I'm not sure if I am interpretting your request correctly, but I think this is what you want: http://jsfiddle.net/mooreinteractive/43jh9hzz/1/
Basically, you are calling the iterate function to run, but then that's it. The function actually needs to also return the value it generates.
I've added to the end of the function, after the for loop completes:
return json;
Do now the function returns the value it generated, but there are some other issues too. When you recursively call the iterate function again inside the iterate function, you actually want to add what it returns to the current json string housing all of your returned value.
So on that line I changed it from:
iterate(obj[property], stack + '.' + property);
to
json += iterate(obj[property], stack + '.' + property);
Now that other value will come back as well inside the main list you were creating in the first run of the function. Ok so that's pretty close, but one more small thing. I think when you added additional surrounding LI, you actually wanted to do an UL. I changed those to ULs and now I think the result is like a UL/LI list representing the text parts of the JSON object.
Again, that may not be exactly what you were after, but I think the main take away is using the function to return the value, not just generate it, then do nothing with it.