Home > Net >  JavaScript - console.log unique values in object "column"
JavaScript - console.log unique values in object "column"

Time:08-22

I'm very new to JavaScript e=and trying to figure out how I can get to certain outputs from an object. I have this object:

const data = [
    {
    Category: "Red",
    date: "11/07/2020",
    predicted: 10,
    actual: 12,
    },
    {
    Category: "Red",
    date: "11/08/2020",
    predicted: 12,
    actual: 13
    },
    {
    Category: "Green",
    date: "11/07/2020",
    predicted: 14,
    actual: 16
    },
    {
    Category: "Green",
    date: "11/08/2020",
    predicted: 10,
    actual: 12
    },
]

export default data;

So now I want to get a list of all unique levels in "Category" and display them via console.log. So that would be:

Red
Green

It's a react app, so I'm trying to put it in my App.js:

import data from './data';

function App() {

  return (
    <div className="App">
      <LineChart />
    </div> 
  );
}

export default App;

The problem is also that I don't know how to select the "column" Category. For now I'm only getting to a point of displying the whole object like this:

  const myArray = Object.values(data);
  console.table(myArray);

CodePudding user response:

Use map to get the categories, then use a Set to get the unique ones:

const data=[{Category:"Red",date:"11/07/2020",predicted:10,actual:12},{Category:"Red",date:"11/08/2020",predicted:12,actual:13},{Category:"Green",date:"11/07/2020",predicted:14,actual:16},{Category:"Green",date:"11/08/2020",predicted:10,actual:12}];

const unique = [...new Set(data.map(e => e.Category))]
console.log(unique)

  • Related