How to map a JSON to create an array in ReactJS?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to map a JSON to create an array in ReactJS? on this date .

I have a JSON and i need to map it and create 2 arrays. One array with field ART and the other with field SALIDA.

console.log(w_data)

reactjs

const VerTotales = ({props}) => {
let data_x = [];
let data_y = [];
let w_data = props.data;
console.log(w_data)

// data_x =
// data_y =

return (
    <Responsive
        xsmall={
            <div style={{width: 140, margin: '1em'}}>

            </div>
        }
        medium={
            <div>
                <GraficoBarrasLineaBasica
                    wp_data_x={data_x}
                    wp_data_y={data_y}
                />
            </div>
        }
    />
);

}

Thanks

Answer

This is probably slightly unneccesarily complicated and I used reduce rather than map but I thought I’d try to provide something for a more general case:

const w_data = {
  1: { id: 1, art: 'A', salida: 100 },
  2: { id: 2, art: 'B', salida: 200 }
};

const collect_by_keys = (array_of_objects, keys) =>
  array_of_objects.reduce(
    (acc, obj) => {
      keys.forEach((k, i) => acc[i].push(obj[k]));
      return acc;
    },
    Array.from({ length: keys.length }, () => [])
  );


const [data_x, data_y] = collect_by_keys(Object.values(w_data), ['art', 'salida']);

console.log(...data_x);
console.log(...data_y);