Defining the data in an array - javascript

How can I use the data stored in the array cottageGallery from this mapped data?
const galleryData = components.map(g => {
return {
cottageGallery: g.cottageGallery,
destinationGallery: g.destinationGallery,
activitiesGallery: g.activitiesGallery,
}
})
I thought it would simply be const cottageGallery = galleryData.cottageGallery but this returns undefined.

Not quite, galleryData is going to be an array not an object as you are using javascript's map method. If you wanted to get the first item of the array you could do the following - [0] being the first item of the array.
const cottageGallery = galleryData[0].cottageGallery;
To log each cottageGallery you could use forEach and do the following:
galleryData.forEach(item => {
console.log(item.cottageGallery);
})

galleryData is an array of the objects returned by the map callback. So you'd use galleryData[index].cottageGallery, where index is in the range 0 through galleryData.length - 1 (or any of the various ways you access entries in an array, such as for-of or forEach or...more here).

map Will return an array so you won't be able to simply access galleryData.cottageGallery. You might want to use .reduce() on your array so the outcome can be the object your were trying to create

You can also use forEach to access object array like below:
galleryData.forEach(a => {
console.log(a.cottageGallery);
})

Related

how to return a modified array

i have a simple function that takes in an array of objects and one object that has been modified. The Goal is to exchange the modified object in the old array of objects and then log the updated array of objects
my Take:
async mutateTodos(currentTodos: ITodos[], editedTodo: ITodos) {
const Index = currentTodos.findIndex((el) => el.id === editedTodo.id);
const updatedTodos = currentTodos.splice(Index, 1, editedTodo);
console.log(updatedTodos);
}
For some Reason, updatedTodos only returns an array containing the old object that was at the index that has been identified properly.
I cant wrap my head around why this doesnt work
splice mutates the array on which the method is called. The return value is not that mutated array, but the slice of the array that was removed from it. In this case it is an array with the old todo.
There are many ways to get the result you want. For instance, you could first create a copy, then call splice on it, and then return that mutated copy.
const updatedTodos = [...currentTodos];
updatedTodos.splice(Index, 1, editedTodo);
console.log(updatedTodos);

What is a proper way to check if an array is in a nested array? [Javascript]

If I have an array const a = [1, 2] and a nested array const nested = [[1,2], [2,3]]
How do I check if array a is in the nested?
I tried using the nested.includes(a), but it doesn't provide the correct output. And I was thinking stringify the array a, but read some comments about we should not compare array using stringify.
So what is a proper way to check if an array is in another array?
includes doesn't work correctly as it compares references - a and nested[0] are different in terms of references.
Take a look at following function:
function includesDeep(array, value) {
return array.some((subArray) => {
return subArray.every(
(subArrayElem, index) => subArrayElem === value[index]
);
});
}
We have to iterate over all elements of given array and check if every element of this sub array is identical to corresponding element from second array (your a). This method detects type mismatches.
You can stringify the arrays to compare whether they are equal in the callback of Array.some :
const a = [1, 2]
const nested = [[1,2], [2,3]]
const containsA = nested.some(e => JSON.stringify(e) == JSON.stringify(a))
console.log(containsA);
if you must compare it without stringification, prepend a unique id to the values and compare that.

Grab values of object inside an object

I am returning a single Object with a nested object, how do I grab the value of the nested object. I want to grab the values of the products list.
{
"status":"Processing","_id":"xx234455",
"products":[
{"_id":"5f81a7988289330","name":"ball ","price":70000,
}],
"returns":20000,"transaction_id":16855
}
You can either iterate it through with .forEach() of products array or accessing elements by index:
const data = {"status":"Processing","_id":"xx234455","products":[{"_id":"5f81a7988289330","name":"ball ","price":70000,}],"returns":20000,"transaction_id":16855}
// iterate
data.products.forEach(e => console.log(e._id))
// by index
console.log(data.products[0]._id)
See from the documentation of .forEach():
The forEach() method executes a provided function once for each array element.
See also the documentation of Array the Access an Array item using the index position section.
In React as the tags are suggesting see also with .map() as:
return <>
{
data && data.products &&
data.products.map((e, i) => <span key={i}>{e._id}</span>)
}
</>
Especially for array usage I suggest to read Lists and Keys from React documentation.

Use Array.map on an 2-dimensional Array

So I have a 2-dimensional Array and want to use a "randomBool" function on each of the elements of the elements in the array.
The "randomBool" function just returns a random boolean:
const randomBool = () => Boolean(Math.round(Math.random()));
this would be the 2-dimensional Array, that I would input:
var test = [
["just","some","random","text"],
[1412,"test",1278391]
]
There is a working for-loop nested in a for-loop:
for (let el of test){
for(let i in el){
el[i] = randomBool();
}
}
I tried this:
test.forEach(el => el.map(el2 => randomBool()));
But it didn't work. Why?
You need to use two nested maps.
const randomBools = test.map(outer => outer.map(inner => randomBool()))
forEach is usually intended to iterate over each item in order to perform some kind of side effect without returning anything and without mutating the original array. For example, printing each item to the console.
map, on the other hand, is intended to take an array and return a new array of the same size, with the values transformed in some way, without mutating the original array. For example, uppercase all the words in a list.
Since you want to return a new 2 dimensional from your existing 2 dimension array with some data transformed, you need to nest your map functions. This will map first over the rows (outer), then the columns (inner). The results of the inner maps will be collected into the outer map and you'll be left with a 2 dimensional array with your new values, all without modifying the original array.

Put an object into an array in AngularJS

I am using ag-grid for an application and it only takes arrays to display the rows. I have an object returned from the API. This call always only returns 1 object. I want to convert the object into an array of length 1.
This is my code:
jobResult.paged().$promise.then(function (results) {
//ag-grid needs the result to be in an array
var arrayResult = [];
angular.forEach(function(results){
arrayResult.push(results);
});
$scope.jobResult = arrayResult;
if ($scope.lastResultGridOptions.api) {
$scope.lastResultGridOptions.api.setRowData($scope.jobResult);
$scope.lastResultGridOptions.api.sizeColumnsToFit();
}
..rest of function
the results object has the data from the API. But the .foreach function does not push the object into the array.
What am I missing?
Your angular.foreach is wrong,
The correct way is, and then you can take the key or value and push to the array,
angular.forEach(results, function(value, key){
//push key or value
arrayResult.push(value);
});
For your explanation, wanting an array length 1 with the results as [0], why not just push the results into the array:
arrayResult.push(results)
If you are trying to create an array from the results then you would want to run the .forEach on the results:
results.forEach(function(res) { arrayResult.push(res); })

Categories

Resources