NextJs Map issue - javascript

I have a array that I want to map properly but I can't do it I always keep getting some error here is the array that I want to map
useful_links:
0: {Register Now: 'some linke'}
1:{Age Calculator: 'some link'}
2: {Join Now: 'some link'}
3:{Cantonment Board Official Website: 'some link'}
I want to map it as so I can use the key as text in anchor tag and those links as href
<a href={some link}>text that are key</a>
thanks in advance!

You can use Object.entries() to get the list of keys / values from an object. For example, using a memo hook to produce a nicer array of objects...
const links = useMemo(
() =>
useful_links.flatMap((obj) =>
Object.entries(obj).map(([text, href]) => ({
href,
text,
}))
),
[useful_links]
);
return (
<ul>
{links.map(({ href, text }, i) => (
<li key={i}>
<a href={href}>{text}</a>
</li>
))}
</ul>
);

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

ES6 map function for tuples/2d arrays

I'm trying to write a map function to return a navbar.
I have an array/dictionary that I want to loop through using the map function that looks something like
[['Text', './link.html'],
['Text2', './link2.html'],
['Text3', './link3.html']]
or else
{'Text', './link.html',
'Text2', './link2.html',
'Text3', './link3.html'}
Whatever type I need to loop through doesn't matter, I just want to loop through sets of 2, ideally I'd want to use tuples, but it doesn't look like that's an option from what I've read.
When looking at solutions that use the dict/object method, I don't know how to access both the key and the value. For ex.
var NavBar = (props) => {
return (
<div id="NavMain">
{Object.keys(props.links).map((link,index) => {
return <NavBarItem link={link} />
{/* Where do I access the key? */}
})}
</div>
)}
If I try to map this as a 2d array, my IDE is showing some error lines underneath 'row', 'text' and '/>' in the code below
var NavBar = () => {
return (
<div id="NavMain">
{this.props.links.map((row,index) => {
return <NavBarItem link=row[1] text=row[0] />
})}
</div>
)}
Other solutions I've looked up are really messy. I'm wondering if there's a clean way to use the map function over sets of 2.
You can use array destructuring inside the .map() like this:
So assuming you have a data set of an array of arrays:
const arr = [
['Text', './link.html'],
['Text2', './link2.html'],
['Text3', './link3.html']
]
var NavBar = (props) => {
return(
<div id="NavMain">
{arr.map(([text, link]) => {
return <NavbarItem link={link} text={text}/>
})}
</div>
)
}
We know the first item is text and the second item is link as expected.
See sandbox for working example: https://codesandbox.io/s/stoic-payne-9zdp3
You almost had it. Try this:
/*
props.links = {
'Text' : './link.html',
'Text2' : './link2.html',
'Text3' : './link3.html'
}
*/
var NavBar = (props) => {
return (
<div id="NavMain">
{Object.keys(props.links).map((key, index) => {
return <NavBarItem link={props.links[key]} text={key} />
})}
</div>
)
}

Mapping an object of array in Reactjs

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

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