I dont know how to use map in this situation - javascript

I wrote the contents of this JSON to the array "heroes", but I don't know how to get "damage", "basicAttack.category" and "specialAttack.category" for mapping. I tried to solve this problem but unfortunately I don't know how.
{
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
and this is my way of mapping and what data I'm trying to get
const item = this.state.heroes.skills.map(item => {
/*i dont have idea how map
<p>{item.damage}</p>
<p>{item.specialAttack.cathegory} + {item.basicAttack.category}</p>
*/
})

Just map over the heroes.skills and you will find the result how to access the value
var heroes ={
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
heroes.skills.map(hero=>{
console.log("damage...........",hero.damage)
console.log("basicAttack.category.........",hero.basicAttack.category)
console.log("specialAttack.category........",hero.specialAttack.category)
})
if you want to render then you have to return it and then render
const heroesDiv = this.state.heroes.skills.map((hero) => (
<>
<p>{item.damage}</p>
<p>{item.specialAttack.category} + {item.basicAttack.category}</p>
</>
))

this.state.heroes.skills.map((item) => {
return `<div><p>${item.damage}</p><p>${item.specialAttack.category} ${item.basicAttack.category}</p></div>`
})

let data = {
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
this is how you can map
return (
<div>
{data.skills.map(item=>
<div key={item.id}>
<h3>{item.id}: {item.basicAttack.name}-{item.basicAttack.category}, {item.specialAttack.name}-{item.specialAttack.category}</h3>
</div>)}
</div>
)

const item = this.state.heroes.skills.map(item => {
return(
<React.Fragment key={item.id}>
<p>{item.damage}</p>
<p>{item.specialAttack.id}</p>
<p>{item.basicAttack.id}</p>
<p>{item.damage}</p>
<React.Fragment>
)
})

You can use JSON.parse to parse the json data and you can easily map as shown in the working snippet below.
var data='{"id":20,"name":"Warrior","skills":[{"id":1,"basicAttack":{"id":2,"name":"Hit1","category":"weakAttack"},"specialAttack":{"id":16,"name":"Special1","category":"spellAttack"},"damage":200},{"id":2,"basicAttack":{"id":3,"name":"Hit2","category":"rangeAttack"},"specialAttack":{"id":17,"name":"Special2","category":"fightAttack"},"damage":100}]}';
var jsondata=JSON.parse(data);
console.log(jsondata.skills[0].damage);
console.log(jsondata.skills[0].basicAttack['category']);
console.log(jsondata.skills[0].specialAttack['category']);

You can do it as this
const item = this.state.heroes.skills.map(item => {
return (
<React.Fragment>
<p>{item.damage}</p>
<p>{item.specialAttack.category} + {item.basicAttack.category}</p>
</React.Fragment>
);
})
Hope it helps

Related

Show values according to condition in reactjs

I'm developing an application in React.JS
I have the array:
array =
[
{
"id": 1,
"user": {
"id": 1,
"name": "user-1"
},
"date": "2021-01-10",
"hour": {
"id": 1,
"time": "09:30:00.000"
},
"duration": {
"id": 1,
"time": 30
},
"type": {
"id": 1,
"name": "type-1"
},
"prof": {
"id": 1,
"name": "prof-1"
},
},
{
"id": 2,
"user": {
"id": 2,
"name": "user-2"
},
"date": "2021-01-14",
"hour": {
"id": 2,
"time": "10:00:00.000"
},
"duration": {
"id": 1,
"time": 45
},
"type": {
"id": 1,
"name": "type-1"
},
"prof": {
"id": 1,
"name": "prof-1"
},
}
]
and:
hour =
[
{
"id": 1,
"time": "09:30:00.000"
},
{
"id": 2,
"time": "10:00:00.000"
},
{
"id": 3,
"time": "10:30:00.000"
}
]
I need to show in a select only the hours that are not available given the equality condition in prof and day.
To try to do this I tried with
{
array.map(item => {
if (item.prof.id === "1" && item.date === "2021-01-14"){
return (
hour.map(elem => {
if (elem.id != item.hour.id){
return <option value={elem.time.id}>{elem.hour.time}</option>
}
})
);
}
})
}
In short I need to show the available hours.
For the example case, it should only show as an option: 09:30:00.000 and 10:30:00.000, as available hours.
How can I do it, suggestions?
your code works perfectly with some little changes:
1. === Operation checks type and value, in this case, prof.id has number type and not equal to string 1.
2. value and text of the options component should be elem.id and elem.time.
const OptionCreator = () => {
const profBusyHours = array
.filter((item) => item.prof.id === 1 && item.date === "2021-01-14")
.map((item) => item.hour.id);
return hour
.filter((elem) => profBusyHours.includes(elem.id) === false)
.map((elem) => (
<option key={elem.id} value={elem.id}>
{elem.time}
</option>
));
};

Replacing a whole block of data in JSON file

I am looking for a way to replace a bunch of data in a JSON file without replacing another part of it:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
],
"compteur": [
{
"id": 8
}
]
}
I manage to get everything that is in between the brackets of "task" in a variable.
My current issue is that I need to replace only what's inside the bracket and not affect the other parts of the file.
This is my code for retrieving the data of "tasks":
function RemoveNode(idToDelete) {
return jsonData.task.filter(function(emp) {
if (emp.id == idToDelete) {
return false;
}
return true;
});
}
var newData = RemoveNode(idToDelete);
arr1 = JSON.stringify(newData, null, 4);
console.log("arr1", arr1);
The console.log gives me:
arr1 [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
]
I actually need to replace this in the original JSON File but I have absolutely no idea how to achieve this.
You can use the spread operator, this will override the task data with your new filtered data
const removeNode = (idToDelete) =>
jsonData.task.filter((emp) => emp.id != idToDelete);
const newData = RemoveNode(idToDelete);
const updatedJSONData = {...jsonData, task: newData};
If your JSON file is not too large, you could consider changing the task array in your JS object (once you've read or imported it into your program) and then re-writing the json file.
JSON file before the program runs:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 6,
"title": "fddsfsd",
"description": "fsdfsd"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}
],
"compteur": [
{
"id": 8
}
]
}
Let's say we want to remove task objects with id=6. The code:
const myFileContents = require('./myFile.json');
const fs = require('fs');
const removeIdFromTasks = (taskList,idToRemove) => {
return taskList.filter(task => task.id!=idToRemove);
}
const writeJsonFile = (fileName,content) => {
fs.writeFile(fileName,content,(err) => {
if(err){
console.error(`Error in writing json file: ${e.message}`);
} else {
console.log(`File written`);
}
})
}
myFileContents.task = removeIdFromTasks(myFileContents.task,6);
writeJsonFile(`myFile.json`,JSON.stringify(myFileContents));
The same file after execution:
{
"task": [
{
"id": 5,
"title": "dave",
"description": "test"
},
{
"id": 7,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
},
{
"id": 8,
"title": "fddsfssdfsdfd",
"description": "fsdfsd"
}],
"compteur": [
{
"id": 8
}]
}

Push parent arrays element and chidren array into new array in javascript

"items": {
"hotdrinks": [
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 25,
"name": "Coffee",
"img": "../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 50,
"name": "Hot Milk",
"img": "../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 70,
"name": "Horlicks",
"img": "../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
],
}
json i want to achieve using javascript. im just new to handling arrays and objects. thanksfound the answer given by Jeeva which works perfectly
future answers are welcome since we can know diffferent methods to achieve the same json object
dataArray = [
{title:"Hotdrinks",
content: [{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 20,
"name": "Tea",
"img": "../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id": "9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price": 80,
"name": "Badam Milk",
"img": "../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}
You can use like this. This can be achieved by iterating the object.
const data = {
"items":{
"hotdrinks":[
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]
}
}
var dataArray = []
for(k in data.items){
var dataObj = {}
dataObj.title = k
dataObj.content = data.items[k] //You can also access the object values by using bracket ([]) notation
dataArray.push(dataObj)
}
console.log(JSON.stringify(dataArray))
The above expected output json is not valid. We can achieve the following.
[{"title":"Hotdrinks"}, {"content": [
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":20,
"name":"Tea",
"img":"../assets/img/HotDrinks/1_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":25,
"name":"Coffee",
"img":"../assets/img/Hot Drinks/2_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":50,
"name":"Hot Milk",
"img":"../assets/img/Hot Drinks/3_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":70,
"name":"Horlicks",
"img":"../assets/img/Hot Drinks/4_udupibhavan.jpg"
},
{
"id":"9aa113b4-1e4e-4cde-bf9d-8358fc78ea4f",
"price":80,
"name":"Badam Milk",
"img":"../assets/img/Hot Drinks/5_udupibhavan.jpg"
}
]}]
If you are okay with this then i'll give you the sample code for the same.

Map a Json file with response from Api in Vuejs

I'm currently getting data from themoviedb.com API. but I discovered the request doesn't include the specific genres for each movie. I created a separate json file that contains all the genres I need. Is there a way I can map data in my genres.json files to the remote API request?
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 80,
"name": "Crime"
},
{
"id": 99,
"name": "Documentary"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 10751,
"name": "Family"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 36,
"name": "History"
},
{
"id": 27,
"name": "Horror"
},
{
"id": 10402,
"name": "Music"
},
{
"id": 9648,
"name": "Mystery"
}
]
}
This is how you might do that.
Basically with Vue, you want to create a computed value that maps over the response from the movie API and adds the genre information to the response.
console.clear()
const genres = [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 80,
"name": "Crime"
},
{
"id": 99,
"name": "Documentary"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 10751,
"name": "Family"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 36,
"name": "History"
},
{
"id": 27,
"name": "Horror"
},
{
"id": 10402,
"name": "Music"
},
{
"id": 9648,
"name": "Mystery"
}
]
new Vue({
el: "#app",
data:{
genres,
movies: null
},
computed:{
moviesWithGenre(){
// if the movies haven't been populated from the AJAX response yet
// return an empty array
if (!this.movies) return []
return this.movies.map(movie => {
return {
// add all the existing movie properties
...movie,
// add the genres
genres: movie.genre_ids
// remove the genres we don't know
.filter(id => this.genres.map(g => g.id).includes(id))
// get the name
.map(id => this.genres.find(g => g.id === id).name)
}
})
}
},
created(){
var url = "https://api.themoviedb.org/3/movie/popular?api_key=8e3003c0c81633dc53b9d15ffa3399e1&language=en-US&page=1"
axios.get(url)
.then(response => this.movies = response.data.results)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id="app">
<ul>
<li v-for="movie in moviesWithGenre">
{{movie.original_title}}
<ul>
<li v-for="g in movie.genres">{{g}}</li>
</ul>
</li>
</ul>
</div>
I do not understand how any of this is related to vue.js as it looks like a pure javascript logic problem.
Here are some advices that could help you :
Rather than keeping an hardcoded list of Categories which is susceptible to get outdated and to break your application, i would recommend you to get them from the api itself :
https://developers.themoviedb.org/3/genres/get-movie-list
When having the result of both your genres and find request you could add the genre names to the object you are getting like so :
// Here the result of the 'genres' call
var genres = [...]
function getGenreName(genreId) {
var genre = genres.find(function(element) {
return element.id === genreId
})
if (!genre) return 'unknownGenre'
return genre.name
}
movieResults.map(function(movieResult) {
movieResult['genreNames'] = movieResult.genre_ids.map(function(genreId) {
return getGenreName(genreId)
})
return movieResult
})

Adding object to parent array based on IDs using Lodash

So I'm having an issue - I'm getting some data from our internal API at work, but it's not in the correct format I need to do what I have to do, so I have to make some transformations.
For this, I decided to use Lodash, however I'm stuck now.
Basically, I'm working with orders, but some of the products are addons to a parent product. I've managed so far to separate these two types of products, but I don't know how I should go about adding an "addons" array as a child to the parent product with matching ID.
Here's a basic stripped example of the output I'd like:
{
"order": {
"orderLines: [
{
"orderId": "foo",
"addons" [
{
...
}
]
},
{
...
}
]
}
}
And here's my current code:
// TODO:
// Match addons to products based on "connectedTo" => "id", then add matching addons as a new array on parent object
// Base data
const data = {
"order": {
"shopOrderId": "19LQ89H",
"createDate": "2017-10-24T13:09:22.325Z",
"orderLines": [
{
"orderId": "19LQ89H",
"product": {
"productName": "Paintball",
},
"id": "59ef3b8036e16f1c84787c1f",
"stringId": "59ef3b8036e16f1c84787c1f"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Ølsmagning",
},
"id": "59ef3b8036e16f1c84787c20",
"stringId": "59ef3b8036e16f1c84787c20"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "CD-indspilning",
},
"id": "59ef3b8136e16f1c84787c21",
"stringId": "59ef3b8136e16f1c84787c21"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Julefrokost",
},
"id": "59ef3b8236e16f1c84787c22",
"stringId": "59ef3b8236e16f1c84787c22"
},
{
"orderId": "19LQ89H",
"product": {
"productName": "Hummer Limousine",
},
"id": "59ef3b8236e16f1c84787c23",
"stringId": "59ef3b8236e16f1c84787c23"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Ekstra kørsel 400",
},
"id": "59ef3b8236e16f1c84787c24",
"stringId": "59ef3b8236e16f1c84787c24"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Drikkevarer",
},
"id": "59ef3b8236e16f1c84787c25",
"stringId": "59ef3b8236e16f1c84787c25"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c23",
"product": {
"productName": "Drikkevarer",
},
"id": "59ef3b8236e16f1c84787c26",
"stringId": "59ef3b8236e16f1c84787c26"
},
{
"orderId": "19LQ89H",
"connectedTo": "59ef3b8236e16f1c84787c22",
"product": {
"productName": "Snaps ad libitum",
},
"id": "59ef3b8236e16f1c84787c27",
"stringId": "59ef3b8236e16f1c84787c27"
}
],
"travelTimes": [
{
"id": "59ef3b8036e16f1c84787c1f-59ef3b8036e16f1c84787c20",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c1f",
"partyPlanToEventId": "59ef3b8036e16f1c84787c20",
"start": "2017-11-15T17:02:59",
"end": "2017-11-15T17:30:00",
"travelTimeString": "27 min.",
"travelTimeMinutes": 28,
"exceedsAvailableTime": false
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8136e16f1c84787c21",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8136e16f1c84787c21",
"start": "2017-11-15T19:52:12",
"end": "2017-11-15T20:00:00",
"travelTimeString": "8 min.",
"travelTimeMinutes": 8,
"exceedsAvailableTime": false
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8236e16f1c84787c22",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8236e16f1c84787c22",
"start": "2017-11-15T12:30:00",
"end": "2017-11-15T13:00:00",
"travelTimeString": "8 min.",
"travelTimeMinutes": 8,
"exceedsAvailableTime": true
},
{
"id": "59ef3b8036e16f1c84787c20-59ef3b8236e16f1c84787c23",
"partyPlanFromEventId": "59ef3b8036e16f1c84787c20",
"partyPlanToEventId": "59ef3b8236e16f1c84787c23",
"start": "2017-11-15T08:30:00",
"end": "2017-11-15T09:00:00",
"travelTimeString": "3 min.",
"travelTimeMinutes": 4,
"exceedsAvailableTime": true
}
],
"id": "59ef3b8236e16f1c84787c28",
"stringId": "59ef3b8236e16f1c84787c28"
}
}
// Transform data
const travelTimes = data.order.travelTimes.map(item => _.omit(item, ['id']) )
const orderLines = _.merge(data.order.orderLines, travelTimes)
const order = _.omit(data.order, ['orderLines', 'travelTimes'])
const orders = _.assign(order, { orderLines })
const addonGroups = _.groupBy(order.orderLines, 'connectedTo')
const addons = _.omit(addonGroups, 'undefined')
const products = _.pick(addonGroups, 'undefined')
const productGroups = _.groupBy(products.undefined, 'stringId')
console.log(productGroups) // All parent products
console.log(addons) // All addon products
const arr1 = _.values(_.flatMap(productGroups))
const arr2 = _.values(_.flatMap(addons))
Code on Codepen.io
Any help is greatly appreciated!
Let me know if I need to explain in further detail.
Not sure if I understood correctly what the expected result is, but I gave it a try anyway.
const orderLines = _(data.order.orderLines)
.map(item => {
if (!item.connectedTo) return _.assignIn(item, { addons: [] });
const match = _.find(data.order.orderLines, { id: item.connectedTo });
match.addons = match.addons || [];
match.addons.push(item);
return null;
})
.compact()
.value();
Check the output here: https://codepen.io/andreiho/pen/YEzQRd?editors=0012

Categories