Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  190] [ 4]  / answers: 1 / hits: 26900  / 5 Years ago, sat, july 20, 2019, 12:00:00

I want to get an array out of the keys on my object but the length should 0 when the Object is empty. The length of array is correct when I try console.log() with the array but my code stucks throwing the following error on my browser and it stops the execution:



RangeError: invalid array length
burger/transformedIngredients<
src/components/Burger/Burger.js:8

5 | const burger = (props) => {
6 | let transformedIngredients = Object.keys(props.ingredients).map(igKey => (
7 | // eslint-disable-next-line max-len,react/no-array-index-key
> 8 | [...Array(props.ingredients[igKey])].map((_, i) => <BurgerIngredient key={igKey + i} type={igKey} />)
9 | )).reduce((arr, el) => (
10 | arr.concat(el)
11 | ), []);


This is the code I'm using:



const burger = (props) => {
let transformedIngredients = Object.keys(props.ingredients).map(igKey => (
// eslint-disable-next-line max-len,react/no-array-index-key
[...Array(props.ingredients[igKey])].map((_, i) => <BurgerIngredient key={igKey + i} type={igKey} />)
)).reduce((arr, el) => (
arr.concat(el)
), []);

if (transformedIngredients.length === 0) {
transformedIngredients = <p>Please add some ingredients!</p>;
}


I am passing ingredients from here:



class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0,
},
totalPrice: 4,
};
render() {
return (
<Fragment>
<Burger ingredients={this.state.ingredients} />
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
/>
</Fragment>
);
}

More From » arrays

 Answers
55

I don't really understand why are you doing an extra mapping of the keys and creating a multidimensional array, but you can change your code to this if you want to render an ingredient for each key:



const burger = (props) => {
let transformedIngredients = Object.keys(props.ingredients).map((igKey, i) => (
<BurgerIngredient key={igKey + i} type={igKey} />
));
}

[#51855] Sunday, July 14, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;