Map a Json file with response from Api in Vuejs - javascript

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

Related

Object has many arrays, loop through each and change some value

I have an object that has a whole host of arrays and properties. There is a property called targetProperty which appears in various places of the object.
I have a function where if the user clicks yes, every instance of that property needs to be reassigned to a new value.
The problem is the function that I used for assigning a new value doesn't work in this senario:
reassingPropertyInObj(obj, status) {
if (typeof obj === 'object' && obj !== null) {
obj.targetProperty = status;
for (const key in obj) {
this.handleExpandCollapseClick(obj[key], status);
}
}
},
Does anyone have a solution for this? Also can't use JSON.parse() or anything like that because the properties need to stay reactive for later reassignment if needed by the user.
Below is an example of one object:
{
"id": 16,
"ref_study_id": "3412333",
"title": "SomePersonNameOne",
"capabilities_available": [
{
"id": 75,
"name": "Clinical Data",
},
{
"id": 538,
"name": "RK's Capability",
}
],
"capabilities_impacted": [],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
{
"id": 6,
"ref_study_id": "123124",
"title": null,
"capabilities_available": [
{
"id": 37,
"name": "Clinical Site Experience,
},
{
"id": 41,
"name": "Experience",
}
],
"capabilities_impacted": [
{
"id": 37,
"name": "Information Exchange",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 39,
"name": "IT/Data Experience",
"is_study_level": false,
"businessImpact": {
"id": 2,
"name": "Medium"
}
},
{
"id": 34,
"name": "Mgmt & Storage",
"is_study_level": false,
"businessImpact": {
"id": 3,
"name": "Minor"
}
}
],
"businessImpact": {
"id": 2,
"name": "Medium"
},
"sites_impacted": [],
"sites_available": []
},
And the property in question is businessImpact. As you can see it appears by itself as a property and inside array (and sometimes those arrays of arrays of their own).
I setup a function like:
arrayOfProperties.forEach((property) => {
obj[property].forEach((o) => {
o.businessImpact = newVal;
});
});
But of course it doesn't go deep enough.

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
}]
}

I dont know how to use map in this situation

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

JSON - search array for value based on unique ID

I have the following JSON Feed:
var data = {
"feeds": {
"regions": [
{
"name": "Lichtenberg",
"id": "01408.b",
"suburbs": [
{ "name": "Fennpfuhl", "views": 76400 },
{ "name": "Lichtenberg", "views": 87895 },
{ "name": "Rummelsberg", "views": 10239 }
]
},
{
"name": "Mitte",
"id": "03442.f",
"suburbs": [
{ "name": "Tiergarten", "views": 82695 },
{ "name": "Mitte", "views": 67234 },
{ "name": "Hansaviertel", "views": 10848 },
{ "name": "Moabit", "views": 67500 }
]
},
{
"name": "Friedrichshain-Kreuzberg",
"id": "01991.o",
"suburbs": [
{ "name": "Friedrichshain", "views": "98494" },
{ "name": "Kreuzberg", "views": "27800" }
]
},
{
"name": "Templehof-Schöneberg",
"id": "01778.k",
"suburbs": [
{ "name": "Friedenau", "views": 76595 },
{ "name": "Schöneberg", "views": 20731 },
{ "name": "Templehof", "views": 58000 },
{ "name": "Mariendorf", "views": 32300 }
]
},
{
"name": "Pankow",
"id": "02761.q",
"suburbs": [
{ "name": "Wießensee", "views": 81294 },
{ "name": "Prenzlauer Berg", "views": 76470 },
{ "name": "Pankow", "views": 90210 }
]
}
],
"branding": [
{
"municipality_id": "01408.b",
"brand_color": "#f9cd90"
},{
"municipality_id": "03442.f",
"brand_color": "#F28123"
},{
"municipality_id": "01991.o",
"brand_color": "#D34E24"
},{
"municipality_id": "01778.k",
"brand_color": "#563F1B"
},{
"municipality_id": "02761.q",
"brand_color": "#38726C"
}
],
"customer": {
"name": "Viktoria Tiedemann",
"date_of_birth": "1981-09-19",
"address": {
"street": "Schönfließer Str 9",
"suburb": "Prenzlauer Berg",
"postcode": "10439"
}
}
}
};
In essence what I want to do is to create an array that contains 3 items:
Name of the region data.feeds.regions.name
Total views of the region
Color of the chart based on the data.feeds.regions.id that is then used as a lookup key to data.branding to get the brand_color of that region.
I've got the answer for parts 1 and 2 from a previous SO Question:
var viewsPerRegion = data.feeds.regions.map(({ name, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0)
}));
My attempt at getting the third one so far is as follows:
var viewsPerRegionStyled = data.feeds.regions.map(({ name, id, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0),
color: if (data.feeds.region.id == data.branding.municipality_id)
{
data.branding.brand_color}
}));
I'm sure I'm completely lost on this one - any help is truly appreciated.
You need to call find on the branding array to find the element with the matching municipality_id and then extract the found brand_color property:
var data={"feeds":{"regions":[{"name":"Lichtenberg","id":"01408.b","suburbs":[{"name":"Fennpfuhl","views":76400},{"name":"Lichtenberg","views":87895},{"name":"Rummelsberg","views":10239}]},{"name":"Mitte","id":"03442.f","suburbs":[{"name":"Tiergarten","views":82695},{"name":"Mitte","views":67234},{"name":"Hansaviertel","views":10848},{"name":"Moabit","views":67500}]},{"name":"Friedrichshain-Kreuzberg","id":"01991.o","suburbs":[{"name":"Friedrichshain","views":"98494"},{"name":"Kreuzberg","views":"27800"}]},{"name":"Templehof-Schöneberg","id":"01778.k","suburbs":[{"name":"Friedenau","views":76595},{"name":"Schöneberg","views":20731},{"name":"Templehof","views":58000},{"name":"Mariendorf","views":32300}]},{"name":"Pankow","id":"02761.q","suburbs":[{"name":"Wießensee","views":81294},{"name":"Prenzlauer Berg","views":76470},{"name":"Pankow","views":90210}]}],"branding":[{"municipality_id":"01408.b","brand_color":"#f9cd90"},{"municipality_id":"03442.f","brand_color":"#F28123"},{"municipality_id":"01991.o","brand_color":"#D34E24"},{"municipality_id":"01778.k","brand_color":"#563F1B"},{"municipality_id":"02761.q","brand_color":"#38726C"}],"customer":{"name":"Viktoria Tiedemann","date_of_birth":"1981-09-19","address":{"street":"Schönfließer Str 9","suburb":"Prenzlauer Berg","postcode":"10439"}}}}
var viewsPerRegionStyled = data.feeds.regions.map(({ name, id, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0),
color: data.feeds.branding.find(
({ municipality_id }) => municipality_id === id
).brand_color
}));
console.log(viewsPerRegionStyled);
Another option is to transform the branding array into an object indexed by municipality_id beforehand, which will allow for simple object lookup, which has less complexity than .find:
var data={"feeds":{"regions":[{"name":"Lichtenberg","id":"01408.b","suburbs":[{"name":"Fennpfuhl","views":76400},{"name":"Lichtenberg","views":87895},{"name":"Rummelsberg","views":10239}]},{"name":"Mitte","id":"03442.f","suburbs":[{"name":"Tiergarten","views":82695},{"name":"Mitte","views":67234},{"name":"Hansaviertel","views":10848},{"name":"Moabit","views":67500}]},{"name":"Friedrichshain-Kreuzberg","id":"01991.o","suburbs":[{"name":"Friedrichshain","views":"98494"},{"name":"Kreuzberg","views":"27800"}]},{"name":"Templehof-Schöneberg","id":"01778.k","suburbs":[{"name":"Friedenau","views":76595},{"name":"Schöneberg","views":20731},{"name":"Templehof","views":58000},{"name":"Mariendorf","views":32300}]},{"name":"Pankow","id":"02761.q","suburbs":[{"name":"Wießensee","views":81294},{"name":"Prenzlauer Berg","views":76470},{"name":"Pankow","views":90210}]}],"branding":[{"municipality_id":"01408.b","brand_color":"#f9cd90"},{"municipality_id":"03442.f","brand_color":"#F28123"},{"municipality_id":"01991.o","brand_color":"#D34E24"},{"municipality_id":"01778.k","brand_color":"#563F1B"},{"municipality_id":"02761.q","brand_color":"#38726C"}],"customer":{"name":"Viktoria Tiedemann","date_of_birth":"1981-09-19","address":{"street":"Schönfließer Str 9","suburb":"Prenzlauer Berg","postcode":"10439"}}}}
var colorsById = data.feeds.branding.reduce((a, { municipality_id, brand_color }) => {
a[municipality_id] = brand_color;
return a;
}, {});
var viewsPerRegionStyled = data.feeds.regions.map(({ name, id, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0),
color: colorsById[id]
}));
console.log(viewsPerRegionStyled);

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