Ad

Array Only Storing Last Variable When Pushing From A JSON In React

- 1 answer

I have the following JSON file called 'testing_numbers.json':

 [{ "number":1,
"number":2,
"number":3,
"number":4,
"number":4,
"number":5,
"number":6,
"number":7,
"number":9,
"number":10,
"number":11}]

All I want to do is push each value to a list through a for loop, then append the list. My React code is like so:

import React, { Component } from 'react';
let values = require('./test_numbers.json');


class App extends Component {
  state = {  }
  render() { 
    const numbers = []
    for (var x in values) {
      numbers.push(values[x].number)
    }
    return ( numbers );
  }
}

export default App;

All I get as an output is the last variable in the JSON (which is 11), and not anything before that. It seems like I have something fundamentally wrong.

I am aware that I could just map the JSON first and then render it, but for my application, it would be better if I extracted data one at a time.

If anyone could help that would be great

Ad

Answer

There is no meaning of having same keys with different values in single object, an object should contain unique key names to simplify your case

Change the json to something like below

   [1,2,3,4,5,6,7,8,9,10,11]

And

   render() { 
     const numbers = []
     for (var x in values) {
          numbers.push(<span key={x}>{x}</span>);
     }
     return ( {numbers} );
  }

Or simply

   render() { 
     return ( 
          {values.map(val => <span key={val}>{val}</span>)}
     );
  }

Or make it individual object for each number. But I don’t see any meaning of having same key with different number in each object instead keep them as array of numbers instead of objects

Ad
source: stackoverflow.com
Ad