Mapping an object of array in Reactjs - javascript

I have an object each key of the object has an array value
const correctionsWords = {
"word": [ "1" , "2"] ,
"word2": ["20" ,"22" ]
};
I did map through each key by using the following code
let correctionList = Object.keys(correctionsWords).map( (key) => {
return (
<div>
{
//console.log( 'After Mapping ' , correctionsWords[key]) [1,2,3]
<ul>
<li>{key} { /* word */}
<ul>
<li>{correctionsWords[key]}</li>
</ul>
</li>
</ul>
}
</div>
); });
the result is * key: word
* value: 1 2
How can I list the values of the array?

Map again each array element:
<ul>
{correctionsWords[key].map(el => (
<li key={el}>{el}</li>
))}
</ul>
I've used a key as the element here. If the elements are not unique better use another key. Also, you need another key for your object mapping in the topmost div:
return (
<div key={key}>
...

I think what you’re looking for is to replace that innermost li with:
{
correctionsWords[key].map(value => <li>{value}</li>)
}

Related

Why does my key give an undefined value even if me passing the key to the object in the form of a string gives me the correct value

Why is the value of categoryDictonary[item] undefined when categoryDictonary["Marvel"] gives ["WandaVision", "Loki", "Moon Knight"] even when the value of item is "Marvel"enter image description here
Here is my code for the same
export default function App() {
var categoryDictonary = {
Marvel: ["WandaVision", "Loki", "Moon Knight"],
SitComs: ["Brooklyn 99", "Big Bang Theory"]};
var categories = Object.keys(categoryDictonary);
function ClickHandler(item) {
console.log(item);
console.log(categoryDictonary["Marvel"]);
console.log(categoryDictonary[item]);
}
return (
<div className="App">
<h2>TV Show Ratings</h2>
<h3>Check out my ratings on some of the most popular TV Shows</h3>
<ul>
{categories.map((item) => {
return (
<li key={item} onClick={() => ClickHandler({ item })}>
{item}
</li>
);
})}
</ul>
</div>
);
}
Your item prop of ClickHandler(item) is not a string which can get the value from the categoryDictionary, it is an object with value {item: "Marvel"} so you have to do categoryDictionary[item.item] to get the correct output.
Edit: Since now you posted the full code, you are already passing the prop item to ClickHandler({ item }) as an object in onClick() you can catch the same in the ClickHandler function by changing its parameters as destructed object function ClickHandler({ item }) then you can directly do categoryDictionary[item].

Error in displaying where there's an a array inside of the object

this is what the data shows inside the console:
I tried displaying it with these but it failed
{Object.entries(value).map(([key, value]) => {
return (
<p key={key}>
<li>
{key}
{value}
{console.log(value.id)} //this will show as undefined
</li>
</p>
);
})}
{value} will show this error :
Objects are not valid as a React child (found: object with keys {color, quantity}). If you meant to render a collection of children, use an array instead.
{value.id} or the {value.name} will show as undefined
With the map, it will say that value.map is not a function
{value.map((value, key) => (
<>
<div>{value.id}</div>
<div>{value.name}</div>
</>
))}
codesandbox: https://codesandbox.io/s/display-the-manipulated-data-dy204r
Your object has a complex structure, and in order to iterate, you need to check if one of the items is Array using Array.isArray(), if yes, then loop them and use, else use the properties directly
Below is the working code of the mock of your object and iteration. I have just logged the values, you can use them in any way you want
let myObj = {
s: [{
color: 'a',
q: '8'
}, {
color: 'b',
q: '2'
}],
name: 'Anne',
id : 18
}
Object.keys(myObj).forEach(function(key) {
if (Array.isArray(myObj[key])) {
myObj[key].forEach(function (item, index) {
console.log(item.color);
console.log(item.q);
});
}
else
console.log(myObj[key])
});
You can do something like this
{Object.entries(value).map((v, key) => {
return (
<p key={key}>
<li>
{key}
{v.name}
{console.log(v.id)} //this will show as undefined
</li>
</p>
);
})}

Loop inside JSX

I have an object similar to this:
{
id: number,
kids: [{
id: number,
kids: [{
id: number,
kids: []
}]
}]
}
So it has property kids which is an array of kids each of which might have its own array of kids. I need to render original object in a tree view list like this:
<ul>
{object.map(item => (
<li>
<p>{item.value}</p>
{item.kids ?
{item.kids.map(item => (
<ul>
<li>
<p>{item.value}</p>
</li>
</ul>
))}
: null
}
</li>
))}
</ul>
So every item of kids will be a <li></li> element with <ul></ul> inside of it if item.kids isn't empty array.
I could keep going like this but it's pretty messy and more importantly I don't know when exactly kids property will be an empty array. So I need somehow loop over original object and it's properties and do something like
while (kid.kids) {
return {kid.kids.map(kid => (
<li>
<p>{kid.value}</p>
<ul>
kid.kids.map(kid => (
etc
))
</ul>
</li>
}))
}
But I can't understand the better way to loop like this.
This is probably best solved with recursion.
const Kids = ({id, kids}) => {
return {
<li key={id}>
<p>{id}</p>
{kids
? (<ul>{kids.map((kid) => <Kids id={kid.id} kids={kid.kids} />)}</ul>)
: null;
}
</li>
}
};

How to access nested JSON graphql object passed into react child component, then list those items?

GraphQL:
{
"data": [
"theProducts": {
"id": "1",
"name": "Fitness bands",
"resistanceLevels": {
"UltraHeavy": 10,
"Heavy": 8,
"Medium": 6 },
"prices": [
16.8,
24.9
13.2
]
}
]
}
I am trying to get the resistanceBands JSON object and the price array to map to the react child component (the query is defined in the parent component) and render the items in a list with bullet points.
Parent Component:
const GET_PRODUCT_DATA = gql`
query getProducts {
theProducts {
id
name
resistanceLevels
prices
}
}
`
// How I am mapping data (name, etc) into the child component
const productsToRender = data.theProducts
{productsToRender.map( product => <ProductDisplay key={product.id} product={ product } />) }
// How can map the object and array to display their items to the ProductDisplay child component?
Child Component:
<div>
<h1>{product.name}</h1> // This works
<p>Resistance Levels | Intensity:</p>
<ul>
<li>{product.resistanceLevels}</li> // This doesnt
</ul>
<p>Prices</p>
<ul>
<li>{product.prices}</li> // This doesnt
</ul>
</div>
You need to use .map() for prices also because that's an array as:
<ul>
{product.prices.map(p => <li>{p}</li>)}
</ul>
Also for resistanceLevels you can use Object.keys and .map() combination as:
const resistanceLevels = {
"UltraHeavy": 10,
"Heavy": 8,
"Medium": 6
};
const result = Object.keys(resistanceLevels)
.map(k => resistanceLevels[k]);
console.log(result);
Read from the documentation:
The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
I guess this gives you the idea how to move further based on the example of prices.map().
const ParentComponent =()=>{
return(
<div>
{productsToRender.map(product => <ProductDisplay key={product.id} product={product }/>) }
</div>
)
}
export default ParentComponent;
const ProductDisplay =(props)=>{
return (
<div>
<h1>{product.name}</h1>
<p>Resistance Levels | Intensity:</p>
<ul>
{Object.entries(props.product.resistanceLevels).map(([key, value]) =>{
return(
<li>{key} : {value}</li>
)
})}
</ul>
<ul>
{
props.product.prices.map(item => {
<li>{item}</li>
})
}
</ul>
</div>
)
}

How can I map through an object in ReactJS?

I have a response like this:
I want to display the name of each object inside this HTML:
{subjects.map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">{ item.name }</span>
</li>
))}
But it throws an error of subjects.map is not a function.
First, I have to define the keys of the objects where it creates an array of keys, where I want to loop through and show the subject.names.
What I also tried is this:
{Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[i]}</span>
</li>
))}
When calling Object.keys it returns a array of the object's keys.
Object.keys({ test: '', test2: ''}) // ['test', 'test2']
When you call Array#map the function you pass will give you 2 arguments;
the item in the array,
the index of the item.
When you want to get the data, you need to use item (or in the example below keyName) instead of i
{Object.keys(subjects).map((keyName, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[keyName]}</span>
</li>
))}
You get this error because your variable subjects is an Object not Array, you can use map() only for Array.
In case of mapping object you can do this:
{
Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">{ subjects[item].name }</span>
</li>
))
}
Use Object.entries() function.
Object.entries(object) return:
[
[key, value],
[key, value],
...
]
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
{Object.entries(subjects).map(([key, subject], i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subject.name}</span>
</li>
))}
Map over the keys of the object using Object.keys():
{Object.keys(yourObject).map(function(key) {
return <div>Key: {key}, Value: {yourObject[key]}</div>;
})}
I use the below Object.entries to easily output the key and the value:
{Object.entries(someObject).map(([key, val], i) => (
<p key={i}>
{key}: {val}
</p>
))}
Do you get an error when you try to map through the object keys, or does it throw something else.
Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:
{ Object.keys(subjects).map((item, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">key: {i} Name: {subjects[item]}</span>
</li>
))}
You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.
I am not sure why Aleksey Potapov marked the answer for deletion but it did solve my problem.
Using Object.keys(subjects).map gave me an array of strings containing the name of each object, while Object.entries(subjects).map gave me an array with all data inside witch it's what I wanted being able to do this:
const dataInfected = Object.entries(dataDay).map((day, i) => {
console.log(day[1].confirmed);
});
I hope it helps the owner of the post or someone else passing by.
Also you can use Lodash to direct convert object to array:
_.toArray({0:{a:4},1:{a:6},2:{a:5}})
[{a:4},{a:6},{a:5}]
In your case:
_.toArray(subjects).map((subject, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">Name: {subject[name]}</span>
</li>
))}

Categories

Resources