I'm student now trying multiple fetch req with diff endpoints (themoviedb API).
//to get movie list
fetch('https://api.themoviedb.org/3/movie/now_playing?api_key='+key+'&language='+lang).then(resp=> resp.json())
//data
results: [
{
adult: false,
backdrop_path: '/faXT8V80JRhnArTAeYXz0Eutpv9.jpg',
genre_ids: [ 16, 28, 12, 35, 10751, 14 ],
id: 315162,
original_language: 'en',
original_title: 'Puss in Boots: The Last Wish',
overview: "Secuela de 'El gato con botas' (2011). El Gato con Botas descubre que su pasión por la aventura le ha pasado factura: ha consumido ocho de sus nueve vidas, por ello emprende un viaje épico para encontrar el mítico Último Deseo y restaurar sus nueve vidas...",
popularity: 5032.178,
poster_path: '/lyP4WNmUiiOgl4g2z7ywE0z6SGF.jpg',
release_date: '2022-12-07',
title: 'El Gato con Botas: El último deseo',
video: false,
vote_average: 8.6,
vote_count: 3032
},
]
now to get list of genres
fetch('https://api.themoviedb.org/3/genre/movie/list?api_key='+key+'&language='+lang).then(resp=>resp.json())
//data
[
{ id: 28, name: 'Acción' },
{ id: 28, name: 'Acción' },
{ id: 12, name: 'Aventura' },
{ id: 16, name: 'Animación' },
{ id: 35, name: 'Comedia' },
{ id: 80, name: 'Crimen' },
{ id: 99, name: 'Documental' },
{ id: 18, name: 'Drama' },
{ id: 10751, name: 'Familia' },
{ id: 14, name: 'Fantasía' },
{ id: 36, name: 'Historia' },
{ id: 27, name: 'Terror' },
{ id: 10402, name: 'Música' },
{ id: 9648, name: 'Misterio' },
{ id: 10749, name: 'Romance' },
{ id: 878, name: 'Ciencia ficción' },
{ id: 10770, name: 'Película de TV' },
{ id: 53, name: 'Suspense' },
{ id: 10752, name: 'Bélica' },
{ id: 37, name: 'Western' }
]
How can i replace genre_ids content for each film (first fetch) with the name of the corresponding id in 2nd fetc? thanks in advance.
I want return a template with all data of movie but for now i only can show id of genre
Luckily, for that you have a one-liner at your disposal:
let genres = [
{ id: 28, name: 'Acción' },
{ id: 28, name: 'Acción' },
{ id: 12, name: 'Aventura' },
{ id: 16, name: 'Animación' },
{ id: 35, name: 'Comedia' },
{ id: 80, name: 'Crimen' },
{ id: 99, name: 'Documental' },
{ id: 18, name: 'Drama' },
{ id: 10751, name: 'Familia' },
{ id: 14, name: 'Fantasía' },
{ id: 36, name: 'Historia' },
{ id: 27, name: 'Terror' },
{ id: 10402, name: 'Música' },
{ id: 9648, name: 'Misterio' },
{ id: 10749, name: 'Romance' },
{ id: 878, name: 'Ciencia ficción' },
{ id: 10770, name: 'Película de TV' },
{ id: 53, name: 'Suspense' },
{ id: 10752, name: 'Bélica' },
{ id: 37, name: 'Western' }
]
let movies = [
{
adult: false,
backdrop_path: '/faXT8V80JRhnArTAeYXz0Eutpv9.jpg',
genre_ids: [ 16, 28, 12, 35, 10751, 14 ],
id: 315162,
original_language: 'en',
original_title: 'Puss in Boots: The Last Wish',
overview: "Secuela de 'El gato con botas' (2011). El Gato con Botas descubre que su pasión por la aventura le ha pasado factura: ha consumido ocho de sus nueve vidas, por ello emprende un viaje épico para encontrar el mítico Último Deseo y restaurar sus nueve vidas...",
popularity: 5032.178,
poster_path: '/lyP4WNmUiiOgl4g2z7ywE0z6SGF.jpg',
release_date: '2022-12-07',
title: 'El Gato con Botas: El último deseo',
video: false,
vote_average: 8.6,
vote_count: 3032
},
]
for (let movie of movies) {
movie.genres = genres.filter((item) => ((movie.genre_ids.indexOf(item.id) >= 0)));
movie.genre_names = movie.genres.map(item => item.name);
}
console.log(movies);
Explanation:
genres
we use the filter function that returns a subset of the array of items that meet the criteria
the criteria is that the id is among the ids of our expectation
genre_names:
we use the map function to get only the names
I was not sure whether you want only the names or the names along with their ids, so we have both, you can restrict the results according to your liking.
Note that we loop movies and perform the same logic for each movie.
You can use an async function to make it easier to perform multiple fetches. Use Array#find to get the corresponding genre from the other array.
async function getData() {
const movieList = await (await fetch('https://api.themoviedb.org/3/movie/now_playing?api_key='+key+'&language='+lang)).json();
const genreList = await (await fetch('https://api.themoviedb.org/3/genre/movie/list?api_key='+key+'&language='+lang)).json();
for (const movie of moveList.results)
movie.genre_ids = movie.genre_ids.map(id => genreList.find(g => g.id === id)?.name);
}
The getNowPlayingWithGenres (async) function below will return a list of current movies sorted by their title and includes a list of human-readable genres.
Note: Just make sure to set the API key.
const
apiUrl = 'https://api.themoviedb.org/3',
apiKey = '<API_KEY>',
lang = 'en-US';
const getGenresIdMap = async () => {
const
res = await fetch(`${apiUrl}/genre/movie/list?api_key=${apiKey}&language=${lang}`),
{ genres } = await res.json();
return genres.reduce((map, { id, name }) => map.set(id, name), new Map);
};
const getNowPlaying = async () => {
const
res = await fetch(`${apiUrl}/movie/now_playing?api_key=${apiKey}&language=${lang}`),
{ results } = await res.json();
return results;
};
const getNowPlayingWithGenres = async () => {
const
genreIdMap = await getGenresIdMap(),
nowPlaying = await getNowPlaying();
return nowPlaying
.map(({ title, genre_ids }) =>
({ title, genres: genre_ids.map(id => genreIdMap.get(id)).sort() }))
.sort((a, b) => a.title.localeCompare(b.title));
}
(async() => {
const result = await getNowPlayingWithGenres();
console.log(result);
})();
.as-console-wrapper { top: 0; max-height: 100% !important; }
Related
I am using nextjs and I am trying to map my array to my getstaticpaths so that I can generate the getstaticprops. However, every time I am trying to map the result, I am getting 'mycatagoriesis not a function' error.
Below is my static site generated page. It is dynamic so I need to use getStaticpaths.
export async function getStaticPaths() {
const mycatagories = await useFetchNavBarCatagoriesSSR();
return {
paths: mycatagories.map((catagory) => ({
params: {
genre: catagory.name,
},
})),
fallback: false,
};
}
export async function getStaticProps(context) {
// Fetch data from external API
if (context.params.genre == "Trending") {
const mydata = useFetchTrendingCatagorySSR();
return {
props: {
mydataz: await mydata,
},
};
} else if (context.params.genre == "Top Rated") {
const mydata = useFetchTopRatedCatagorySSR();
return {
props: {
mydataz: await mydata,
},
};
} else if (context.params.genre !== null) {
const mygenrechosen = context.params.genre;
const mycatagories = await useFetchNavBarCatagoriesSSR();
const myparseddata = await useFetchParserforGenreResults(
mycatagories,
mygenrechosen
);
const myresultdataafterparsing = await useFetchMovieGenreResultsSSR(
myparseddata
);
return {
props: {
mydataz: await myresultdataafterparsing,
},
};
}
}
function genre({ mydataz }) {
return (
<div>
{/* {console.log(props)} */}
{/* <Navbar /> */}
<div>Hello</div>
<Moviegenreresults movies={mydataz} />
</div>
);
}
export default genre;
Below is the useFetchNavBarCatagoriesSSR() function.
export default async function useFetchNavBarCatagoriesSSG() {
const response = await fetch(
`https://api.themoviedb.org/3/genre/movie/list?api_key=f70b3ca617a5d8978429e375c55a4fa2&language=en-US`
);
const fetchedgenres = await response.json();
await fetchedgenres.genres.push({ name: "Trending" });
await fetchedgenres.genres.push({ name: "Top Rated" });
console.log(
return fetchedgenres;
}
Below is what the useFetchNavBarCatagoriesSSG() returns.
{
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' },
{ id: 10749, name: 'Romance' },
{ id: 878, name: 'Science Fiction' },
{ id: 10770, name: 'TV Movie' },
{ id: 53, name: 'Thriller' },
{ id: 10752, name: 'War' },
{ id: 37, name: 'Western' },
{ name: 'Trending' },
{ name: 'Top Rated' }
]
}
I am thinking my problem is that my useFetchNavBarCatagoriesSSG() is returning an array inside an object instead of just an array. If that is the case, does anyone know a quick way to extract the array from the object. I tried mapping useFetchNavBarCatagoriesSSG().genre but it did not work. It gives me the error cannot read property map of undefined.
Any thoughts?
useFetchNavBarCatagoriesSSG().genres
not
useFetchNavBarCatagoriesSSG().genre
I am trying to improve the time complexity and quality of the code snippet below.
I am iterating through one array to check if the element this array exists in the object, should this be true it should return the name matching the element id in the object.
how can I do this without having a nested loop?
Can someone tell me what I can do to make this algo better, please?
Thank you all in advance.
let genres = [28, 12, 878];
data = {
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',
},
{
id: 10749,
name: 'Romance',
},
{
id: 878,
name: 'Science Fiction',
},
{
id: 10770,
name: 'TV Movie',
},
{
id: 53,
name: 'Thriller',
},
{
id: 10752,
name: 'War',
},
{
id: 37,
name: 'Western',
},
],
};
const getGenreName = () => {
let result = [];
for (let genre of data.genres) {
//console.log("genre", genre.name)
for (let id of genres) {
//console.log('id',genres[i])
if (id === genre.id) result.push(genre.name);
}
}
console.log(result);
};
getGenreName();
You can use reduce and includes as others have already shown. This will make the code a bit cleaner, but not change the overall runtime complexity. To improve runtime complexity you may need to use a different data structure.
For instance instead of
let genres = [1,2,3,4];
as a simple array, you could use a Set, which has a better lookup performance.
let genres = new Set([1,2,3,4]);
Then you can use this as follows
let result = data.genres
.filter(g => genres.has(g.id))
.map(g => g.name);
and won't need any explict for loops
The simplest improvement would probably be converting genres to a Set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
and use the has method to check if each id in the data is a member of the set of chosen genres.
You can also convert the data to a map with the ids as the keys in order to look up by id quickly instead of looping, but that is only faster if the data is reused many times.
JavaScript #reduce in the example outlined below would have O(n) time complexity. This only loops through the array once. We could use filter, and map but it would result in us having to loop through the array twice.
const getGenreName = () => {
const genreSet = new Set(genres);
return data.genres.reduce((accumulator, { id, name }) => {
if (genreSet.has(id)) accumulator.push(name);
return accumulator;
}, []);
};
console.log(getGenreName()); // [ 'Action', 'Adventure', 'Science Fiction' ]
We are initializing the reducer to start with the array [], or an empty array, and then checking to see if the genre property of the object is included in the genres array, if it isn't, return the accumulator, if it is, append it to the end of the accumulator and return it.
You wanted this in one loop, so here it is:
let result = [];
data.genres.forEach(function (e) {
if (genres.includes(e.id)) result.push(e.name);
});
console.log(result);
In case you were wondering about forEach, here's a very good reference: https://www.w3schools.com/jsref/jsref_foreach.asp
The current time complexity is O(MN) where M is the length of data.genres and N is the length of genres.
Time complexity in JavaScript depends on which engine you use, but in most cases you can use a Map to reduce this time complexity to O(max{N,M}):
const getGenreName = () => {
const dataGenresMap = new Map( // O(M)
data.genres.map(({id,...params}) => [id,params]) // O(M)
)
let result = []
for (let id of genres) { // O(N)
if (dataGenresMap.has(id)) result.push(dataGenresMap.get(id).name) // O(1)
}
console.log(result)
}
If you might be doing this more than once then I'd recommend using a Map. By creating a hash map, retrieving genre names per id is much more performant.
let genres = [28, 12, 878];
data = {
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',
},
{
id: 10749,
name: 'Romance',
},
{
id: 878,
name: 'Science Fiction',
},
{
id: 10770,
name: 'TV Movie',
},
{
id: 53,
name: 'Thriller',
},
{
id: 10752,
name: 'War',
},
{
id: 37,
name: 'Western',
},
],
};
const genreById = new Map ();
data.genres.forEach(({id, name}) => genreById.set(id, name));
const pushMapValueIfTruthy = map => array => key => {
const val = map.get(key);
if (val) {
array.push(val);
}
};
/** function that takes an array, then id, and pushes corresponding name (if exists) into the array. */
const pushGenreNaneIfExists = pushMapValueIfTruthy(genreById);
const getGenreNames = (ids) => {
result = [];
ids.forEach(pushGenreNaneIfExists(result));
return result;
};
console.log(getGenreNames(genres));
this is how the object look:
let data = [
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 1',
price: '200',
},
},
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 2',
price: '230',
},
},
{
brandId: '7878',
brand: 'Nike',
item: {
name: 'Nike 1',
price: '305',
},
}
];
i want the item object will merge if the object have the same brandID :
let data = [
{
brandId: '12345',
brand: 'Adidas',
item: [
{
name: 'Adidas 1',
price: '200',
},
{
name: 'Adidas 2',
price: '230',
},
],
},
{
brandId: '7878',
brand: 'Nike',
item: {
name: 'Nike 2',
price: '316',
},
},
];
is there any javascript syntax or method to do this ? and with an explanation will be very nice, Thank You
(Assuming that your output is just a typo and name/price doesn't actually changes) You can use array reduce
let data = [
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 1',
price: '200',
},
},
{
brandId: '12345',
brand: 'Adidas',
item: {
name: 'Adidas 2',
price: '230',
},
},
{
brandId: '7878',
brand: 'Nike',
item: {
name: 'Nike 1',
price: '305',
},
}
];
const mergedItems = data.reduce((acc, curr) => {
// check if current exist on the accumulator
const exist = acc.find(brand => brand.brandId === curr.brandId);
// if it does, add the item on it
if (exist) {
return acc.map((brand) => {
if (brand.brandId === exist.brandId) {
return {
...brand,
item: brand.item.concat(curr.item),
}
}
})
}
// if it doesnt, add it on accumulator, and make the item array
return acc.concat({
...curr,
item: [
curr.item
]
})
})
(I wrote the code manually and not tested)
You can simply achieve this result using Map
let data = [
{
brandId: "12345",
brand: "Adidas",
item: {
name: "Adidas 1",
price: "200",
},
},
{
brandId: "12345",
brand: "Adidas",
item: {
name: "Adidas 2",
price: "230",
},
},
{
brandId: "7878",
brand: "Nike",
item: {
name: "Nike 1",
price: "305",
},
},
];
const dict = new Map();
data.forEach((o) => {
dict.get(o.brandId)
? dict.get(o.brandId).item.push(o.item)
: dict.set(o.brandId, { ...o, item: [o.item] });
});
const result = [];
for (let [k, v] of dict) {
v.item.length === 1 ? result.push({ ...v, item: v.item[0] }) : result.push(v);
}
console.log(result);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
I want to get the total price of nested arrays in a specific category e.g: Hot Drinks.
Here is a sample of what I have now, so I want to filter out and get the total price of Hot Drinks Category only.
[
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
You can apply a filter method on the array and then just add the values on the filtered array. Something like below:
let prod = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
];
function getPriceByCategory(category, products) {
let price = 0;
products.forEach(orders => {
orders.orderItems.filter(order => order.category == category).forEach(item => {
price += item.price;
});
});
return price;
}
const totalPrice = getPriceByCategory('Hot Drinks', prod);
alert(totalPrice);
Sample JS Fiddle: https://jsfiddle.net/sagarag05/qwzju53f/9/
const filterBy = 'Hot Drinks';
const items = [
{
totalPrice: 30,
_id: '6014fa4324e125599eaa72b5',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Breakfast',
name: 'food name 1',
price: 3,
qty: 1,
},
{
_id: '6014fa4324e125599eaa747s5',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 5,
},
{
_id: '6014fa4324e125599eaa74767',
category: 'Hot Drinks',
name: 'drink name 2',
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: '6014fa4324e125599eaa7276e',
orderItems: [
{
_id: '6014fa4324e125599eaa747ss',
category: 'Hot Drinks',
name: 'drink name 1',
price: 3,
qty: 6,
},
],
},
]
const sumOf = (items, filterBy) => {
let totalPrice = 0;
items.forEach(item => {
item.orderItems.forEach(orderItem => {
if (orderItem.category === filterBy) {
totalPrice += orderItem.price;
}
})
})
return totalPrice;
}
console.log(sumOf(items, filterBy))
let sum = 0;
allOrders.forEach(order => {
order.orderItems.forEach(item => {
if(item.category=='Hot Drinks') {
sum+ = item.price * item.qty
}});
});
sum has the total price for Hot Drinks
Assuming you named that information as data:
Generate a big array of all the "orderItems"
For each of those elements sum the price if the category is "Hot Drinks"
const totalPrice = data
.reduce((acc, { orderItems }) => [...acc, ...orderItems], [])
.reduce((acc, { category, price }) => category === "Hot Drinks" ? acc + price : acc, 0);
console.log(totalPrice); // 10
Use flatMap and reduce or alternatively using forEach and destructuring
const total = (arr, text) =>
arr
.flatMap(({ orderItems }) => orderItems)
.reduce((acc, { category, price }) =>
(acc + (category === text ? price : 0)), 0);
// alternatively
const total2 = (arr, text, acc = 0) => {
arr.forEach(({ orderItems }) =>
orderItems.forEach(
({ category, price }) => (category === text && (acc += price))
)
);
return acc;
};
const data = [
{
totalPrice: 30,
_id: "6014fa4324e125599eaa72b5",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Breakfast",
name: "food name 1",
price: 3,
qty: 1,
},
{
_id: "6014fa4324e125599eaa747s5",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 5,
},
{
_id: "6014fa4324e125599eaa74767",
category: "Hot Drinks",
name: "drink name 2",
price: 4,
qty: 2,
},
],
},
{
totalPrice: 23,
_id: "6014fa4324e125599eaa7276e",
orderItems: [
{
_id: "6014fa4324e125599eaa747ss",
category: "Hot Drinks",
name: "drink name 1",
price: 3,
qty: 6,
},
],
},
];
console.log(total(data, 'Hot Drinks'))
console.log(total2(data, 'Hot Drinks'))
I have this array on input :
const categories = [
{ id: 9, name: 'General Knowledge' },
{ id: 10, name: 'Entertainment: Books' },
{ id: 11, name: 'Entertainment: Film' },
{ id: 12, name: 'Entertainment: Music' },
{ id: 13, name: 'Entertainment: Musicals & Theatres' },
{ id: 14, name: 'Entertainment: Television' },
{ id: 15, name: 'Entertainment: Video Games' },
{ id: 16, name: 'Entertainment: Board Games' },
{ id: 17, name: 'Science & Nature' },
{ id: 18, name: 'Science: Computers' },
{ id: 19, name: 'Science: Mathematics' },
{ id: 20, name: 'Mythology' },
{ id: 21, name: 'Sports' },
{ id: 22, name: 'Geography' },
{ id: 23, name: 'History' },
{ id: 24, name: 'Politics' },
{ id: 25, name: 'Art' },
{ id: 26, name: 'Celebrities' },
{ id: 27, name: 'Animals' },
{ id: 28, name: 'Vehicles' },
{ id: 29, name: 'Entertainment: Comics' },
{ id: 30, name: 'Science: Gadgets' },
{ id: 31, name: 'Entertainment: Japanese Anime & Manga' },
{ id: 32, name: 'Entertainment: Cartoon & Animations' }
]
I need to translate all the keys name of my objects.
For that, I use the google translation API.
here is the code :
googleTranslate.translate(categories.map(i => i.name), 'en', 'fr', function(err, translations) {
console.log(translations.map(tr => tr.translatedText))
})
So the result is :
[ 'Culture générale',
'Divertissement: livres',
'Divertissement: Film',
'Divertissement: Musique',
'Divertissement: comédies musicales et théâtres',
'Divertissement: Télévision',
'Divertissement: jeux vidéo',
'Divertissement: jeux de société',
'Science et nature',
'Science: Informatique',
'Science: Mathématiques',
'Mythologie',
'Des sports',
'La géographie',
'L\'histoire',
'Politique',
'Art',
'Célébrités',
'Animaux',
'Véhicules',
'Divertissement: BD',
'Science: Gadgets',
'Divertissement: anime et manga japonais',
'Divertissement: dessin animé et animations' ]
But I would like to keep the structure of the first array. Only update the keys name with the translations.
Output :
const categories = [
{ id: 9, name: 'Culture générale' },
{ id: 10, name: 'Divertissement: livres' },
{ id: 11, name: 'Divertissement: Film' },
{ id: 12, name: 'Divertissement: Musique' },
{ id: 13, name: 'Divertissement: comédies musicales et théâtres' },
{ id: 14, name: 'Divertissement: Télévision' },
{ id: 15, name: 'Divertissement: jeux vidéo' },
{ id: 16, name: 'Divertissement: jeux de société' },
{ id: 17, name: 'Science et nature' },
{ id: 18, name: 'Science: Informatique' },
{ id: 19, name: 'Science: Mathématiques' },
{ id: 20, name: 'Mythologie' },
{ id: 21, name: 'Des sports' },
{ id: 22, name: 'La géographie' },
{ id: 23, name: 'L\'histoire' },
{ id: 24, name: 'Politique' },
{ id: 25, name: 'Art' },
{ id: 26, name: 'Célébrités' },
{ id: 27, name: 'Animaux' },
{ id: 28, name: 'Véhicules' },
{ id: 29, name: 'Divertissement: BD' },
{ id: 30, name: 'Science: Gadgets' },
{ id: 31, name: 'Divertissement: anime et manga japonais' },
{ id: 32, name: 'Divertissement: dessin animé et animations' }
]
I have not found how to do it yet.
Thanks in advance for your time.
The simplest way is:
googleTranslate.translate(categories.map(i => i.name), 'en', 'fr', function(err, translations) {
console.log(translations.map(tr => {
id: tr.id,
name: tr.name
}
))
})
You could recreate the old structure after the translation:
const categories [...];
const translatedCategories = new Array();
googleTranslate.translate(categories.map(i => i.name), 'en', 'fr', function(err, translations) {
translations.forEach((tr, index) => {
translatedCategories.push({
id: categories[index].id,
name: tr.translatedText
});
});
});
if you want to just change the name of your categories, this should do the trick...
function replace(categories, result) {
for (let i = 0; i < categories.length; i++) {
categories[i].name = result[i];
}
return categories;
}
have a look at the snippet, it's simple.
const categories = [
{ id: 9, name: 'General Knowledge' },
{ id: 10, name: 'Entertainment: Books' },
{ id: 11, name: 'Entertainment: Film' },
{ id: 12, name: 'Entertainment: Music' },
{ id: 13, name: 'Entertainment: Musicals & Theatres' },
{ id: 14, name: 'Entertainment: Television' },
{ id: 15, name: 'Entertainment: Video Games' },
{ id: 16, name: 'Entertainment: Board Games' },
{ id: 17, name: 'Science & Nature' },
{ id: 18, name: 'Science: Computers' },
{ id: 19, name: 'Science: Mathematics' },
{ id: 20, name: 'Mythology' },
{ id: 21, name: 'Sports' },
{ id: 22, name: 'Geography' },
{ id: 23, name: 'History' },
{ id: 24, name: 'Politics' },
{ id: 25, name: 'Art' },
{ id: 26, name: 'Celebrities' },
{ id: 27, name: 'Animals' },
{ id: 28, name: 'Vehicles' },
{ id: 29, name: 'Entertainment: Comics' },
{ id: 30, name: 'Science: Gadgets' },
{ id: 31, name: 'Entertainment: Japanese Anime & Manga' },
{ id: 32, name: 'Entertainment: Cartoon & Animations' }
]
const result = [ 'Culture générale',
'Divertissement: livres',
'Divertissement: Film',
'Divertissement: Musique',
'Divertissement: comédies musicales et théâtres',
'Divertissement: Télévision',
'Divertissement: jeux vidéo',
'Divertissement: jeux de société',
'Science et nature',
'Science: Informatique',
'Science: Mathématiques',
'Mythologie',
'Des sports',
'La géographie',
'L\'histoire',
'Politique',
'Art',
'Célébrités',
'Animaux',
'Véhicules',
'Divertissement: BD',
'Science: Gadgets',
'Divertissement: anime et manga japonais',
'Divertissement: dessin animé et animations' ];
let catNew = replace(categories, result);
console.log(catNew);
function replace(categories, result) {
for (let i = 0; i < categories.length; i++) {
categories[i].name = result[i];
}
return categories;
}