How to convert API data into local language data? - javascript

I am working on a reactJS+Flux Project.I am trying to convert my website into multi-language. I already have my dictionary of all the possible value coming from my API. I want to replace actual value of API with my dictionary value.
for example:
from API I am getting following format data:
data = {
basic: {
name: "ajay kumar",
country: "India",
State: "Maharashtra",
City: "Mumbai"
}
}
in my hindi dictionary I already got all value like:
data= {
hindi: {
"country" : {
"India" : "भारत"
},
state: {
"Andaman & Nicobar Islands": "अंदमान अँड निकोबार आयलँड्स",
"Andhra Pradesh": "आंध्र प्रदेश",
"Arunachal Pradesh": "अरुणाचल प्रदेश",
"Assam": "आसाम",
"Bihar": "बिहार",
"Maharashtra": "महाराष्ट्र"
},
"city" :{
"Mumbai" : "मुंबई"
}
}
}
I want to change all of my value from given dictionary.

First of all make sure that your dictionary can not be a simple:
{englishWord1: hindiWord1,
....
englishWordn: hindiWordn}
If it can not, I would extract the keys from data.basic with Object.keys(object) then I would define I function that map the word in your dictionary with the ones in your object (translate(section, word, dictionary) => [section, translatedWord]).
With Object.keys(object) you obtain an array of keys that correspond to the sections in you dictionary (Country,State ecc) then with map you transform each element in the array for di that you use translate(..) and you obtain an array of translated word: [[section1:translatedWord1],...[sectionn,translatedWordn]]. Then with a function that take array and return an object (arrayToObject([])=>{}) you'll have your translated object.
//This is your dictionary
engToHindi = {
Country : {
India: 'valueIndia',
},
State: {
Maharashtra: 'valueMaharashtra',
},
City :{
Mumbai: 'valueMumbai',
}
}
data = {
basic: {
Name: "ajay kumar",
Country: "India",
State: "Maharashtra",
City: "Mumbai"
}
}
function arrayToObject(array){
object = {}
array.map(x => {object[x[0]] = x[1]});
return object;
}
function translate(section, word, dictionary){
// If the section doesn't exist do not transalate
if (dictionary[section] === undefined){
return [section, word];
}
translatedWord = dictionary[section][word];
return [section, translatedWord];
}
arrayToTransform = Object.keys(data.basic).map(key => translate(key, data.basic[key], engToHindi))
console.log(arrayToTransform)
transformed = arrayToObject(arrayToTransform);
console.log(transformed);
Please make sure that you need the dictionary divided in sections.

Related

Object with values as keys that store each individual object related to it using reduce: Javascript

just working through a problem and was wondering if anyone could shed some light on this issue I'm having. I'm supposed to take an array of objects (a set of parks) and I need to take a key from an object nested within it, use that as a new key and store an array of every object related by that same value we pulled for the key. Here's an example:
I'm working with data that looks a lot like this:
const myParks = [
{
name: "Garden of the Gods",
areaInSquareKm: 200,
location: {
state: "Colorado"
}
},
{
name: "Acadia",
areaInSquareKm: 198.6,
location: {
state: "Maine"
}
},
{
name: "Mountain Pass",
areaInSquareKm: 400.6,
location: {
state: "Colorado"
}
},
{
name: "Newleaf Forest",
areaInSquareKm: 150.4,
location: {
state: "Maine"
}
},
];
And I need to take the location.state value and use that as individual keys of a new object, then assign each key a value of the object with a related state. If the state is Maine, the key should contain the entire object with the related state:
{
"Maine": [
{
name: "Acadia",
areaInSquareKm: 198.6,
location: {
state: "Maine"
}
},
{
name: "Newleaf Forest",
areaInSquareKm: 150.4,
location: {
state: "Maine"
}
},
]
};
I was trying to do it like so:
function parkByState(parks) {
let stateParks = parks.reduce((result, park) => {
result[park.location.state] = parks.filter(park => { park.location.state })
}, {});
return stateParks
};
I can't for the life of me figure out how to do this properly. I can't change the structure, they MUST be assembled within an object, with the state names as keys, and have an array containing each individual park if the state matches the key. I just seriously don't know what I'm doing wrong. I keep getting an error:
Uncaught TypeError: Cannot set properties of undefined (setting 'Maine')
at <anonymous>:37:35
at Array.reduce (<anonymous>)
at parkByState (<anonymous>:36:26)
at <anonymous>:42:18
I'm relatively new to JavaScript and would love if anyone can shed some light on this. I needed to use the reduce() method to assemble the object. I figured using filter to filter the objects into each key would have made sense, but I can't seem to get the two methods to work together properly. You don't have to feed me the answer, but at the very least, please tell me what I'm doing wrong here. I've tried several different ways to do this and none seem to work. If I'm missing a key point of how to use these methods, please let me know what I can do to better understand what they are trying to do. I really appreciate all the help and I apologize if this is a dumb question. I'm just trying to understand how to reassemble an array of each park, stored in a key that is pulled from the state of each park. I'm sorry if the question isn't worded the absolute best, I really want to get better at this kind of stuff so I'm just trying to understand what I'm doing wrong here and how I can achieve the desired result.
Thank you in advance.
Without reduce we can do :
const myParks = [
{
name: "Garden of the Gods",
areaInSquareKm: 200,
location: {
state: "Colorado"
}
},
{
name: "Acadia",
areaInSquareKm: 198.6,
location: {
state: "Maine"
}
},
{
name: "Mountain Pass",
areaInSquareKm: 400.6,
location: {
state: "Colorado"
}
},
{
name: "Newleaf Forest",
areaInSquareKm: 150.4,
location: {
state: "Maine"
}
},
];
const stateNames = new Set(myParks.map(area => {
return area.location.state;
}));
const collectionsByStateName = {};
[...stateNames].forEach(stateName => {
collectionsByStateName[stateName] = [];
myParks.forEach(area => {
if(stateName === area.location.state) {
collectionsByStateName[stateName].push(area);
}
})
});
console.log(collectionsByStateName);
The callback that you pass to .reduce() should return a value. When you give an arrow funnction a body {} it must include return if you wish to return a value from it, otherwise, it will return undefined. Because you don't return anything from your reduce callback it currently returns undefined, so on the next iteration result will be undefined. This causes your error as you're trying to set a value of undefind which you can't do. Moreover, your .filter() needs to return a truthy value when you want to keep the value, and a falsy value when you want to discard it.
While you can do some modifications to your code to get the filter to work, I recommend not filtering at all. Instead, check what the current state is of the current park, and if that state is already in result, push to the existing array, otherwise, create a new key in result for that state with a new array holding the current state:
const myParks = [ { name: "Garden of the Gods", areaInSquareKm: 200, location: { state: "Colorado" } }, { name: "Acadia", areaInSquareKm: 198.6, location: { state: "Maine" } }, { name: "Mountain Pass", areaInSquareKm: 400.6, location: { state: "Colorado" } }, { name: "Newleaf Forest", areaInSquareKm: 150.4, location: { state: "Maine" } }, ];
function parkByState(parks) {
let stateParks = parks.reduce((result, park) => {
const key = park.location.state;
result[key] ??= []; // set `key` to an empty array if it doesn't exist, (similar to result[key] = result[key] || [];)
result[key].push(park);
return result;
}, {});
return stateParks;
};
console.log(parkByState(myParks));
As you said that you're new to JavaScript, I would do away with .reduce() here though. This particular example doesn't really need to use .reudce() and can be made more readable by using a for loop. I've also replace the nullish-coalescing operator with an if-statement which might ready more clearly if you're unfamiliar with ??
function parkByState(parks) {
const stateParks = {};
for(const park of parks) {
const key = park.location.state;
if(!stateParks[key])
stateParks[key] = [];
stateParks[key].push(park);
}
return stateParks;
}

Cannot populate an array from JSON object in Angular

I have the following JSON object:
Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" }
This JSON is a response data returned from a get call(HttpClient Angular).
So now, I need to populate this into the following to display as a dropdown list.
countryList: { countryCode: string; countryName :string }[];
I tried doing the following :
for (const key in resData) {
if (resData.hasOwnProperty(key)) {
var obj ={
countryCode :key,
countryName : resData[key]
}
this.countryList.push(obj);
}
}
But when I execute I'm getting this error
"_this.countryList.push is not a function"
What am I doing wrong?
The code you’ve posted only defines the type of countryList. You need to also initialise it as an empty array before you can push to it - see below.
countryList: { countryCode: string;countryName :string }[] = [];
You can get entries from the object and then map it to the array of objects:
Object.entries(countries).map(([key, value]) => ({
countryCode: key,
countryName: value
}))
you need to declare countryList as list.
var resData={ JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" };
countryList=[];
for (const key in resData) {
if (resData.hasOwnProperty(key)) {
var obj ={
countryCode :key,
countryName : resData[key]
}
countryList.push(obj);
}
}
console.log(countryList)

Destructuring data in state from external file in React

I want to receive all city name's from an external .js file to compare them later with the input value. The problem is when I destructure like const { city } = this.state.cities; and console.log, it return undefined.
const cities = [
{
key: 1,
city: "Cambridge"
},
{
key: 2,
city: "Durango"
},
{
key: 3,
city: "Atlanta"
},
{
key: 4,
city: "Sacramento"
},
{
key: 2,
city: "San Francisco"
}
];
export default cities;
and JSX file
class Filters extends React.Component {
state = {
cities: cities,
categories: categories,
types: types,
salaries: salary
};
How do I can get to cities without setting a specific index of object?
If you don't want to get an object by array index, you can get it by key or city like:
cities.find(e => e.key === 1)
or
cities.find(e => e.city === 'city')

React / Javascript - how to filter data received to a filtered list of columns?

I receive data / an array with objects. each object has country - city and shops (in that city).
For example:
USA - Los Angeles - shop1
Italy - Milan - shop2
Italy - Rome - shopXY
var data = [
{country: "Italy", city: "Milan", shop: "shop123"},
{country: "Italy", city: "Rome", shop: "shop2"},
{country: "USA", city: "Los Angeles", shop: "shopXY"}
]
I have 3 columns and I want to show only once Italy, then when I click on it, I show Milan and Rome, then based on whether I click Rome or Milan the corresponding shops.
Would it be good practise to:
get all the data, then create a new array of objects, so I dont have duplicate countries, cities etc.
Use filter method- but how could I filter it, how can check for duplicates
without storing them in a new array or the like?
Anything else?
I tried to research but couldn't really find anything and even if someone just has some tips, it would be great as I'm totally lost. Thanks!!!!
PS. I don't want to use any filter libraries for that as I m trying to do it myself.
I would recommend using a javascript object, as opposed to making a new array, with the processed data.
The property/value semantics of a Javascript object have following advantages
1.) Duplicates are automatically taken care of: Using the country as a key, you either create a new sub-object mapping shops to cities, or you simply expand an already present one
2.) Ease of access: Finding a Country/shop becomes as simple as data['Italy']['Rome']
Seems like a perfect fit for your use-case. The static way of defining such an object, in adherence to your example woud be:
var data = {
"Italy": {
"Milan": ["shop123"],
"Rome": ["shop2"]
},
"USA": {
"Los Angeles": ["shopXY"]
}
}
MTTI answers is good, and to get to it, I'd use a reduce
const newData = data.reduce((acc, val) => {
if (!acc[val.country]) {
acc[val.country] = { [val.city]: [val.shop] };
return acc;
}
if (!acc[val.country][val.city]) {
acc[val.country][val.city] = [val.shop];
return acc;
}
acc[val.country][val.city].push(val.shop);
return acc;
}, {})
So in the end you'll get an object like
{
Italy: {
Rome: ['Shop123'],
Milan: ['Shop12']
},
USA: {
"San Francisco": ['Shop420']
}
}
You can use the following script to filter the data after that you can iterate on the result of the script to show the data as you want.
var data = [{
country: "Italy",
city: "Milan",
shop: "shop123"
},
{
country: "Italy",
city: "Rome",
shop: "shop2"
},
{
country: "USA",
city: "Los Angeles",
shop: "shopXY"
},
]
var result = {};
data.forEach(function (item) {
if (result[item.country]) {
result[item.country][item.city] = item.shop
} else {
result[item.country] = {};
result[item.country][item.city] = item.shop
}
});
The out put will be like -
{
"Italy": {
"Milan": "shop123",
"Rome": "shop2"
},
"USA": {
"Los Angeles": "shopXY"
}
}

How to create dynamic table headers from JSON in React?

I have a JSON array of objects, I want to create a dynamic table columns/headers based on it in React.
The data:
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
]
I want to iterate through the array, get the key and add extra fields.
So far I have:
columns() {
return Object.keys(Example[0]).map((key) => {
return {
cityName: key,
capital: false,
};
});
}
I get the keys, but they are unordered (random) and the extra field is added to all the objects. I want to get each key to use it as table header (column name) and be able to change capital for each object.
How can I do that in React?
You can use Array.map for this.
example = [
{
id: 0,
city: 'New York',
},
{
id: 1,
city: 'Paris',
},
];
example.map((obj) => {
return {
CITY : obj.city,
ID : obj.id
// Do whatever with the objects
}
})
arr => arr && arr[0] ? object.keys(arr[0]) : [];
make sure all items in array have same keys

Categories

Resources