Problems rendering the api data on the screen to the user - javascript

how do I map these items in the component to render on the screen, I'm not sure because it's an array of objects and it contains "pacotes" which is also an array of objects, I made a filter to render only "pacotes"
useEffect(() => {
const filtrando = teste.filter((item) => (item.pacotes))
console.log(filtrando)
}, [])

filter takes a callback that outputs a truthy or falsy value. It's used to remove elements from an array that don't match. An array is truthy, so your filter won't do anything, unless one of your items doesn't have a pacotes key.
You are probably looking for .map. const filtrando = teste.map((item) => (item.pacotes)) will output an array that is only the pacotes array from the original items.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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

Pushing objects in an array returns duplicate objects in react

I am trying to push objects to my array State using the onChnage method. But every time my array returns the duplicate value, not the real value. I tried so many times to fix this issue. But I can't.
const [variant, setVariant] = React.useState([]);
values.filter((valuesData) => (!valuesData.hasVariants ? setVariant((data) => [...data,{ productId:valuesData._id}]): setVariantStatus(false)));
First index is always duplicated

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.

Passing associative array as props not working

I have a React application which handles rooms and their statistics.
Previously, I had the code set up to pass as props to the next component:
the raw statistics (not a concern for the question)
an array of all the rooms set up as follows
I figured it would be simpler for me, though, to have the list of all rooms as an associative array where the keys of each element is the same as the ID it contains. To do that, I utilized a code similar to this in a for loop:
roomsList[rooms[v].ID] = rooms[v];
So that the result would be:
[a001: {...}, a002: {...}, ...]
I then proceeded to pass this style of array, and not the standard one with a numeric index, as a prop to the next component as such:
<StatsBreakdown stats={computedStats.current} roomsList={roomsList} />
BUT
Now, the next component sees that prop as an empty array.
Even more weirdly, if I initialize that roomsList array with a random value [0] and then do the same process, I end up with:
I cannot cycle through the array with .map, and, according to JS, the length is actually 0, it's not only Google Chrome.
Is there something I'm missing about the way JSX, JS or React work?
Your original roomsList was an array of objects, whose indices were 0,1,2 etc. roomsList[rooms[v].ID] = rooms[v]; implies you are inserting elements not using a number but an alphanumeric string. Hence your resulting array is no longer an array but an object.
So we can cycle over the object using Object.keys().
const renderRoomDets = Object.keys(roomsList).map(room => {
roomOwner = roomsList[room].owner_id;
return (
<div>
<p>{`Room Owner ${roomOwner}`}</p>
</div>
);
});
But I believe your original form is ideal, because you are reaping no special benefits from this notation.
A better alternative maybe using .find() or .findIndex() if you want iterate over an array based on a specific property.
const matchedRoom = roomsList.find(room => room.ID === 'Srf4323')
Iterate the new array using its keys not indexes.
Or even better store your data in an actual object instead of an array since you're using strings for ids.
First define your object like so:
let data = {};
Then start adding records to it. I'd suggest deleting the ID attribute of the object since you're storing it in the key of your record, it's redundant, and it won't go anywhere unless u delete the entry.
data[ID] = row;
To delete the ID attribute (optional):
row.ID = null;
delete row.ID;
Then iterate through it using
for(let key in data){}

Categories

Resources