Destructuring data in state from external file in React - javascript

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

Related

How can I extract and pair the values of an array based object

I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)

Sequelize magic method returning null

Just a bit confused as to why this magic method is returning null. It's probably very simple, but I'm using methods I wouldn't normally (bulkingCreating) and can't currently see it.
Association: Country.hasOne(Capital, { foreignKey: 'countryId' });
Populating dummy data:
const countries = await Country.bulkCreate([
{ name: 'England' },
{ name: 'Spain' },
{ name: 'France' },
{ name: 'Canada' }
]);
const capitals = await Capital.bulkCreate([
{ name: 'London' },
{ name: 'Madrid'},
{ name: 'Paris' },
{ name: 'Ottawa' }
]);
countries.forEach((country, index) => {
country.setCapital(capitals[index]);
});
const country = await Country.findOne({where: {name: 'Spain'}});
console.log(country.name, Object.keys(country.__proto__)); // Spain / magic methods
const capital = await country.getCapital();
console.log(capital); // null
The table:
Am I wrong in thinking country.getCapital() should return the relevant entry?
As you might guess setCapital should be an async function because it makes changes in DB so you need to use for instead of forEach method that does not support async callbacks:
let index = 0;
for (const country of countries) {
await country.setCapital(capitals[index]);
index += 1;
}
It would be better to create countries one by one and create capitals for them not relying on the same indexes of both collections (DB might return created records in a different order).
If you are using Sequelize 5.14+, you can do this in 1 bulkCreate using include option.
const countries = await Country.bulkCreate([
{
name: 'England',
Capital: { // This keyname should be matching with model name.
name: 'London'
}
},
{
name: 'Spain',
Capital: {
name: 'Madrid'
}
},
...
],
{
include: Capital,
returning: true // If Postgres, add this if you want the created object to be returned.
}
);

How to get JSON keys and add extra fields?

I'm trying to get the key of these json objects in order to create a new object with extra filed to create table headers in a React app. JSON data:
let example = [
{
id: 1,
city: 'New York',
},
{
id: 2,
city: 'Paris',
},
]
The function:
getKeys() {
return example.map((key) => {
return {
cityName: key, // gets the whole array
capital: false,
};
});
}
I tries Object.keys( example);, it returns integers; 0, 1.
How can I get the keys in this case? Thanks.
You are trying to map the keys for an array since example is an array. If the data are consistent throughout the array get the first element example[0] and do Object.keys().
So Object.keys(example[0])
There's no need to get the keys if you just want to add a property to the items in the array. I think there's a misunderstanding about .map, which gives you a single item/object in the array, not the keys.
Something like this perhaps?
let example = [{
id: 1,
city: 'New York',
}, {
id: 2,
city: 'Paris',
}];
const modifiedArray = function(arr) {
return arr.map(item => {
return {
id: item.id,
cityName: item.city,
capital: false,
};
})
}
const newArray = modifiedArray (example);
console.log(newArray )

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

How to convert API data into local language data?

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.

Categories

Resources