Looping within const in ReactJS - reactjs

This is really minimal... but I haven't been able to figure this out.
const compose_url = (id, key) =>
`${id}/image/_/${key}`;
const get_images = compose_url(
this.props.dataset_id, // pass in prefix (2018_1_25)
get_image_arrays // This returns an array with two arrays e.g. [["img1.png"], ["img2.png"]]
);
I want this to return "2018_1-25/img1.png" and "2018_1-25/img2.png", but I'm only getting that for the first array, ("2018_1-25/img1.png") not for the second one. How could I loop through this to add the prefix to both images?
Please help... I haven't found documentation or examples on how to do this.

You need to update compose_url() function here, and make sure you always pass array as second of the vairable.
const compose_url = (date, imageArray) =>
imageArray.map((eachImage) => `${id}/image/_/${eachImage}`);
hope this helps.

const get_images = [];
const { dataset_id: id } = this.props;
get_images_array.forEach(arr => {
arr.forEach(path => {
get_images.push(
compose_url(
id,
path
)
);
}
});
EDIT:
I took a different approach to other answers and instead of modifying the compose_url method, I worked off of the the given data. This approach iterates over the top level array (get_images_array) and then iterates over each of the arrays in get_images_array. For each path in the inner arrays, the result of compose_url is pushed onto the get_images result array.

try this.
const compose_url = (id, arr) => {
return arr.map((ar) => (
`${id}/image/_/${ar}`
));
};
This function will return [ "2018_1_25/image/_/img1.png", "2018_1_25/image/_/img2.png" ]

You can simply map over the array like
const compose_url = (id, arr) => {
return [].concat(arr.map(data => [].concat(data.map(key) => `${id}/${key}`)));
}
const get_images = compose_url(
this.props.dataset_id, // pass in prefix (2018_1_25)
get_image_arrays // This returns an array with two arrays e.g. [["img1.png"], ["img2.png"]]
);

Related

Iterating through a JSON array and returning a subset of elements

I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.

Is the insertion order for an array every going to be changed after performing a map

If I have an array and I want to call map() to that array. Will the result returned from map ever going to have different order from array?
const array = [1,2,3,4,5,6,7,8,9];
const mappedArray = array.map((num) => {
return num * num;
})
console.log(mappedArray);
The mappedArray will ever be [1,4,9,16,25,36,49,64,81]
or it is possible that it changes to something else (not the same order)?
What if I make an API call inside the map like the following
const mappedArray = array.map(async (num) => {
return await api(num);
})
// remote API
function api(num) {
return dynamoDbClient.getItem(num);
}
No, map will always iterate through the array in order. Unless the array is changed elsewhere in your code, the order of the resulting array will not change. The output will always be the same if the input is the same.
Run this code 1000 times and the array will be the same every time.
const array = [1,2,3,4,5,6,7,8,9];
const mappedArray = array.map((num) => {
return num * num;
})
console.log(mappedArray);

react check array values based on specific keys returning true/false if values found

I am trying to figure out how to do this but can't seem to wrap my head around it..
I have an address object
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123 Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}
I want to check for any key that has a value but only specific keys
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
I want to check all keys in objProps against my address object and if any one of them contains a value return true (doesn't matter if its 1 or all 6).. If all keys don't contain a value then return false (Sometimes I will get an address object that has all null values)
I've tried various ways to accomplish this but have failed in each one.
The variation I am working on now is using reduce. While it doesn't meet my needs I thought I could check the resulting array and if length was greater than 0 than I have my answer..
Work-in-progress:
function hasAddressData(obj: any) {
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const keysWithData = objProps.reduce((accumulator, key) => {
const propExistsOnObj = obj.hasOwnProperty(key);
let keyHasData = [];
if (obj[key].length > 0 ) {
keyHasData = obj[key]
}
if (!propExistsOnObj) {
accumulator.push(key);
} else if (keyHasData) {
const equalValueKeyIndex = accumulator.indexOf(key);
accumulator.splice(equalValueKeyIndex, 1);
}
return accumulator;
});
return keysWithData;
}
The above is messed up I know and doesn't work.. Just learning this stuff.. anyone have a suggestion or comment?
Check that .some of the objProps, when looked up on the obj, contain a value. (Either with Boolean or by comparing against '')
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123 Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"",
"addressLine2":"",
"city":"",
"state":"Indiana",
"state_code":"",
"zip":"",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":""
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);
function checkKeys(target, props) {
return props.some((prop) => {
return target.hasOwnProperty(prop) && target[prop];
});
}
Explanation: some iterates through the props you want to check, returning true immediately when one is found (i.e. the callback returns true). If no props are found (i.e. no callback returns true), some returns false.
hasOwnProperty ensures that you are only checking properties on target, and not looking up the prototype chain. target[prop] checks for a truthy value. You may need to modify this last check if you're going to be handling values other than strings.

React : Pushing result of map() to an array

Hello I am trying to map through an array of objects and push them to a new array.
My ISSUE : only the last item of the object is being pushed to the new array
I believe this has to do with React life cycle methods but I don't know where I should I loop and push the values to the array to get the full list
//My object in an array named states
var states = [{"_id":"Virginia","name":"Virginia","abbreviation":"VN","__v":0},{"_id":"North Carolina","name":"North Carolina","abbreviation":"NC","__v":0},{"_id":"California","name":"California","abbreviation":"CA","__v":0}];
export function StateSelect()
{
**EDIT 1**
const options = [];
function getStates()
{
//This is how I am looping through it and adding to an array
{ states.length > 0 &&
states.map(item =>
(
console.log(`ITEM: ${JSON.stringify(item)}`),
options.push([{ value: `${item.name}`, label: `${item.name}`}])
))
}
}
return( {getStates()}: );
}
Thank you
It looks like your getStates() might not even be returning anything... but assuming it is, I believe you should be able to accomplish this using a forEach() fn in order to push values into your options array... Try adding the following into your map:
states.map((item) => {
console.log(`ITEM: ${JSON.stringify(item)}`);
let processed = 0;
item.forEach((i) => {
options.push([{ value: `${i.name}`, label: `${i.name}`}]);
processed++;
if(processed === item.length) {
// callback fn, or return
}
}
.map usually used to return another result, you could just use .forEach
In fact, you don't really need to declare options at all, just use .map on state to return the result would be fine.
return states.length > 0 && states.map(({ name }) => {
return { value: name, label: name };
});

How to use variable inside if from same function?

Now I would like to get a variable from if inside same function as if like below.
renderItemBox() {
const { store } = this.props;
const currentScreen = this.props.navigation.state.routeName;
AsyncStorage.getItem('openingGenre')
.then((openingGenreValue) => {
if (currentScreen === 'EachShopGenreScreen') {
if (openingGenreValue === 'food') {
const items = this.store.restourantStore.Items;
} else {
Alert.alert('予期せぬ不具合が発生いたしました。再度お試し下さい');
}
});
return items.map((value, index) => (
//////
)
However, this code is not working, I cannot get "items" from IF on items.map~~~~
Why this is happening?
Could someone help me.
You need to declare items using let as an empty array in the function scope then do your if statement.
Or at least that's one way of doing it.
Btw this is more of a JavaScript question.

Resources