Ruban
Ruban

Reputation: 123

How can I use a config json file in React with where condition

I have a json file called config.json:

[
  {
    "id":8,
    "data":["student","teacher"]
   },
   {
    "id":9,
    "data":["student"]
   },
   {
    "id":10,
    "data":["student","teacher","parents"]
   }
]

table.js:

import configData from "../config/config.json";
const data =configData.map(configData, 8);
console.log(data );

how can i read data from json when id=8 using reactjs.I tried above but showing error.

config file is a local components inside the project.

Upvotes: 1

Views: 2224

Answers (2)

Aashish Garg
Aashish Garg

Reputation: 46

import configData from "../config/config.json";

const data = configData.find(x => x.id === 8)

This finds you the required data element within your configData with id = 8, and stores it in data

Upvotes: 2

webcoder
webcoder

Reputation: 1517

You can use filter or find method: with filter method:

import configData from "../config/config.json";
const data = configData.filter(function(item) {
  return item.id ===9
});

//or using ES6 you can do
const data = configData.filter(item => item.id ===9);

console.log(data );

or if you want a single object not an array you can use find method:

import configData from "../config/config.json";
const data = configData.find(item => item.id ===9); //this will return a single object

console.log(data );

Upvotes: 2

Related Questions