Couple of problems:
You need to explicitly add a
returnstatement in the callback function of themap()methodreturn <li>{cardData[keys].name}</li>cardDataseems to be an array. If that's the case, then no need to useObject.keys(...). Callmap()method directly on the array{cardData.map((obj) => { return <li>{obj.name}</li> })}Alternate option is to remove the curly brackets. This will allow you to remove the
returnkeyword and theliwill be returned implicitly{cardData.map((obj) => <li>{obj.name}</li>)}
Note: Don't forget to add the key prop on the li element:
{cardData.map((obj) => (
<li key={obj.id}>{obj.name}</li>
))}
Edit
If cardData is not an array, and is just an object of the following form:
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
...
}
then use the following code:
{Object.keys(cardData).map(key => {
return <li>{cardData[key].name}</li>
})}
OR use the implicit return by removing the curly brackets:
{Object.keys(cardData).map(key => (
<li>{cardData[key].name}</li>
))}
Answer from Yousaf on Stack OverflowCouple of problems:
You need to explicitly add a
returnstatement in the callback function of themap()methodreturn <li>{cardData[keys].name}</li>cardDataseems to be an array. If that's the case, then no need to useObject.keys(...). Callmap()method directly on the array{cardData.map((obj) => { return <li>{obj.name}</li> })}Alternate option is to remove the curly brackets. This will allow you to remove the
returnkeyword and theliwill be returned implicitly{cardData.map((obj) => <li>{obj.name}</li>)}
Note: Don't forget to add the key prop on the li element:
{cardData.map((obj) => (
<li key={obj.id}>{obj.name}</li>
))}
Edit
If cardData is not an array, and is just an object of the following form:
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
...
}
then use the following code:
{Object.keys(cardData).map(key => {
return <li>{cardData[key].name}</li>
})}
OR use the implicit return by removing the curly brackets:
{Object.keys(cardData).map(key => (
<li>{cardData[key].name}</li>
))}
You have to explicitly return values from map.
Since cardData is already an array so you can use map directly on arrays, no need to take the keys and then process them to get the name.
CODESANDBOX
<>
<ul>
{cardData.map((o) => {
return <li key={o.id}>{o.name}</li>;
})}
</ul>
</>
REACT: Render the keys of only one object
Extract keys alongside values from object
react js get value from object based on key name [closed]
reactjs - Accessing key name in key-value pairs on props object in React - Stack Overflow
I have an object with nested objects in db that I receive in my app.
if (this.state.cartItems) {
const cartItems = Object.entries(this.state.cartItems);
storeItem = cartItems.map((cartItem, index) => (
<StoreItemimgUrl={cartItem.imgUrl}key={index}brand={cartItem.brand}description={cartItem.description}price={cartItem.price}/>
));
}
I want to make a delete button, and for that I need the key of specific object. How can I extract that key and send it alongside other properties?
Are you asking how to access properties with problematic names like -LMgzJGM78f0BHbPf8cc?
If so, instead of the object.property notation, you can access object properties by the property name using the square brackets syntax:
let obj = { color: 'blue' }
let prop = 'color'
console.log(obj.color);
console.log(obj['color']);
console.log(obj[prop]);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
If not, please try to make more clear what your current problem is.
I'd suggest to transform the object received from the Firebase to array in this way:
const formattedTasks = [];
const tasks = Object.values(data.tasks);
tasks.forEach(task =>
Object.entries(task).forEach(([key, value]) =>
formattedTasks.push({ name: key, data: value })
)
);
So, you'll map through formattedTasks array.
Here's a working example: https://codesandbox.io/s/l348nnkv9q
Right now I am making an app using the twitch api. There channels endpoint returns a data object. Since it's an object I can't map over it like normally I would if it was an array.
Thus why I am using Objects.keys(myObj) to turn the object into an array, however it's only an array of it's keys, and in order to get an array of the keys and values I have to do something like this
var myObj = {
name: 'zack',
age: 27,
height: 511
};
var newArr = Object.keys(myObj);
console.log(newArr);
var mappedArr = newArr.map(function(i) {
return [i, myObj[i]];
});
console.log(mappedArr);the last console log is an array of my key:value pairs, but each key/value pair is in its own array.
I just want to take the object data, map through it, and pass certain parts of the objects data to a child component as props like this: https://gist.github.com/laere/eaf0fa4eb90b731f92e9
How can I achieve the same thing? Here is my code: https://gist.github.com/laere/ac142dedd253087ffda6
UPDATE I solved the issue. i realized I was being mentally retarded and not just calling the values within my component like this {myObj.name} or {myObj.whatevervalueithas}. I was overcomplicating it thinking I had to map over the data like my olther components. What a day.
State is an object, so you can access any value by:
this.state[key]
Use any loop map, forEach etc to iterate the array and access the value by this.state[key], like this:
a.forEach(el => console.log(this.state[el]))
Check this snippet:
let state = {a: 1, b: 2};
let arr = ['a', 'b'];
let values = arr.map(el => state[el])
console.log(values);
Thanks to array access syntax, you can access a property of an object (like state), using a variable:
let state = {a: 1, b: 2}
let myKey = 'a';
console.log(state[myKey]) // 1
So to get all the values for an array of keys, map over your array of keys and retrieve the value of the state at each key.
let values = keys.map(key => this.state[key])
You can filter the questions by a particular key of the object first and then do the map. Let's say id with value 1.
return (
<div>
{questions
.filter(({ id }) => id === "1")
.map(question => (
<Question
key={question.id}
questionNum={question.id}
title={question.title}
answers={question.answers}
/>
))}
</div>
)
If I got it right, I guess you can do the same using map itself
Assume you have the below array
const questions = [
{
id: '1',
section: 's1',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
},
{
id: '2',
title: 'Question 2',
answers: [
"answer a",
"answer b",
"answer c",
"answer d",
]
}]
and now you wanna just pull out the answers key alone then you can do something like
const result = questions.map((question) => {answers: question.answers}); // where the specific key here is answers
If you get an object like the following from console logging destructured props:
{
dashboardinfo: {goals: [{goal: 20000}]}
}
You need to use props.dashboardinfo.goals[0].goal to get the value.
Your props contains the object "dashboardinfo" so you need to do
props.dashboardinfo.goals[0].goal
or a better way is to destructure your props object like this
const Goal = ({dashboardinfo: { goals }}) => {
...
goals[0].goal
...
}
Object.keys(options.object).map((key, i) => (
<option key={i} value={key}>
{options.object[key]}
</option>
)
In this way, without knowing the keys, you can access all of then, looping and access the values.
<select {...rest}>
{options.map((option, i) => {
const optionKey = Object.entries(option)[0][0]
const optionValue = Object.entries(option)[0][1]
return (
<option key={i} value={optionKey}>
{optionValue}
</option>
);
})}
</select>
Method Object.entries() returns an array of [key, value] pairs, so if you are sure your option have only one property then you can use the above snippet, if not then you must iterate over the array returned by Object.entries()
The best way to get the key attribute value that you set is to just pass it as another attribute as well that has meaning. For example, I often do this:
const userListItems = users.map(user => {
return <UserListItem
key={ user.id }
id={ user.id }
name={ user.name }
});
or in your case:
this.props.albums.map(function(albumDetails) {
return (<div className="artistDetail" key={albumDetails.id} data-id={ albumDetails.id } onClick={component.getTracks}>
<img src={albumDetails.imageSrc} />
<p><a href="#" >{albumDetails.name}</a></p>
</div>)
It seems redundant, but I think its more explicit because key is a purely react implementation concept, which could mean something different than id, even though I almost always use unique IDs as my key values. If you want to have id when you reference the object, just pass it in.
The key is for React's internal use and won't display in the HTML and Console, you just have to use the id to retrieve that unique component. eg:
getTracks: function (e) {
console.log(e.target.id?e.target.id:e.target);
}
this.props.albums.map(function(albumDetails) {
return (<div key id={ albumDetails.id } onClick={component.getTracks} className="artistDetail" >
<img src={albumDetails.imageSrc} />
<p><a href="#" >{albumDetails.name}</a></p>
</div>)
}
And also you don't need to pass value to the key attribute.Value is completely optional.