如何访问JS对象中嵌套项目的索引? [英] How to access index of nested items in JS object?
问题描述
这可能是我应该添加解决此问题的地方,我坚持使用该索引来返回整个对象,我的目标是打印单击项的索引,请有人帮忙
This is where I should probably add something to fix the issue, I am stuck with this index that returns the whole object, my goal is to print the index of clicked item, please someone help
const listItems = this.state.list.map((item, index) =>
Object.values(item).map(nestedItem => (
<div>
<Card.Header>
{nestedItem.title}
</Card.Header>
<div class="ui buttons fluid">
<button
onClick={() => this.upvote(index)}
>
UPVOTE
</button>
</div>
))
);
下面的代码正常工作,只是我在此示例中对要查找的2
索引进行了硬编码
The code below is working correctly it's just that I hard coded the index I am looking for 2
in this example
console.log(Object.keys(this.state.list[index])[2]);
这是整个对象,我现在需要的只是它的索引
And this is the whole object, all I need now is the index of it
0: "-LORYsI9mLP8mu_2BTKS"
1: "-LORZVOq8SMUgTOPgpXK"
2: "-LORZtqZeg3nyOW4p9I1"
3: "-LOYbElg81jbPtao2nl4"
4: "-LOZ3pNNMAOtNxMWNDi4"
推荐答案
是否只需要内部映射的索引?我仍然对这个问题感到困惑,但是也许像这样.
Do you just need the index of the inner mapping? I'm confused by the question still, but perhaps something like this.
const listItems = this.state.list.map((item, index) =>
Object.values(item).map((nestedItem, nestedIndex) => (
<div>
<Card.Header>
{nestedItem.title}
</Card.Header>
<div class="ui buttons fluid">
<button
onClick={() => this.upvote(index, nestedIndex)}
>
UPVOTE
</button>
</div>
))
);
如果这行不通,您能发表一个数据结构示例吗?
If this doesn't work, could you post an example of your data structure?
这里是文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Syntax
这篇关于如何访问JS对象中嵌套项目的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!