Grab values of object inside an object - javascript

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.

Related

Problems rendering the api data on the screen to the user

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

How to filter one element of JSON array when specific value exist in it

I have const allAlertsData which is JSON array with elements as objects. I want to filter specific element of array once it's property trainId === idTrain.
const idTrain is taken from useParams.
So out of whole allAlertsData, I want to filter out only element[0] if idTrain will be TLK-12345.
Can You please suggest how to filter only one element of JSON array based on matching it's specific property ?
You can use the find() method of an Array:
const foundAlert = allAlertsData.find(alert => alert.trainId === trainId)
The find method will return the first element where the provided testing function evaluates truthy. (source)

When we render react Components from an iterable using Array.prototype.map() how is the index generated, and how does react uses it?

I would like to know, if the content of the iterating object has any effect on the index being generated, for example if the iterating objects have identical key values, will it generate identical indices or will the key prop accepted will get affected ?
example i was using this array:
[
{id: 1, bank: "HDFC", account:"345345"},
{id: 1, bank: "Stabdard_Chartered", account:"678567"},
]
I want to know, if the index argument of map() has any dependency on the first / item argument. As I observed so recently. All the items in the array was having the same id as 1 and the keys were automatically converted to .$1 for some reason, however when we changed id to unique values, it started working as expected
The key isn't generated automaticly you need to add your own key (see example), react uses the key to track which element needs to be updated on every rerender.
{array.map((item) => {
return <p key={item.id}>{item.name}</p>
})
You may also use the index of the map as your key, though many advise against it, the index is the 2nd (optional) argument passed to the map like this
{array.map((item, index) => {
return <p key={index}>{item.name}</p>
})
If jus just want a simple key the second argument of map is a index you could use it as a key
objects.map(objs,index) => { return <Obj key={index} /> }

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){}

Defining the data in an array

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

Categories

Resources