问题
Let me explain this really quickly, when I fetch data from the database, there's a parent object and inside there is an array of objects, what I'm looking to achieve is to write the correct path so I can access specific items in the db.
When receiving the data I store two variables like so:
for (let a in obj) {
list.push(obj[a]);
keys.push(a);
}
this.setState({
list: list,
keys: keys,
});
Executing this code will print the following:
console.log(this.state.keys[index]);
HZlgUZ21vKbungnxaxDJXrTUr2z1
This always returns the exact parent object id
But the issue is that I cannot access the index of the nested items:
console.log(this.state.list[index]);
Object {-LORYsI9mLP8mu_2BTKS: Object, -LORZVOq8SMUgTOPgpXK: Object, -LORZtqZeg3nyOW4p9I1: Object, -LOYbElg81jbPtao2nl4: Object}
What I'm looking for is that nested item ID not all the values
i attached a picture of the database so you can see how it looks like
Here's a minimal representation of the view:
const listItems = this.state.list.map((item, index) =>
Object.values(item).map(nestedItem => (
<div>
{nestedItem.title}
<button
onClick={() => this.update(index)}
>
CLICK
</button>
</div>
))
);
It's pretty easy to solve it's just that I am still learning main concepts of programming but this nested objects always makes me frustrated. Please someone come to my rescue
回答1:
Can you try to apply the below concept in your example?
Consider you have a JSON structure like
var obj = {
a: {
blue:16,
green:30,
red:39
},
b: {
orange:56,
yellow:34,
white:35
},
c: {
black:3,
brown:43,
purple:12
}
};
Now, when you run a for...in loop over this object
for (let key in obj) {
list.push(obj[key]);
keys.push(a);
}
obj[key] will return the value {blue:16,green:30,red:39} which ultimately is pushed into the list array
If you want the values blue, green and red, you can do something like
Object.keys(obj[key]); //will return an array ['blue', 'green', 'red']
来源:https://stackoverflow.com/questions/52763824/the-index-of-a-js-object-returns-all-values-in-object-rather-than-the-actual-ind