Home > front end >  Javascript Filtering JSON data
Javascript Filtering JSON data

Time:04-21

Sample JSON data:

{
  "assignments": [{
    "date": "2022-04-01",
    "lName": "lastname",
    "uId": "12345",
    "uCode": "LName1",
    "fName": "FName1 ",
    "aName": "AsignmentName1",
    "aId": "998"
  }]
}

I'd like to filter the following data to get a specific element's contents based on searching for an assignment name.

For instance in SQL like terms

Select * FROM assignments WHERE `aName` = 'AssignmentName1'

I'm sure this is simple but having trouble with methods for how to accomplish it.

Thanks

CodePudding user response:

I am new here, but if you have access to modern day JavaScript, I would do something like:

const data = JSON.parse('{"assignments":[{"date":"2022-04-01","lName":"lastname","uId":"12345","uCode":"LName1","fName":"FName1 ","aName":"AsignmentName1","aId":"998"}]}';
const yourMatch = data.assignments.find(c => c.aName === 'AssignmentName1');
  • Since data.assignments is an array, you can call the find() function on it. This functions takes a 'search'-function/lambda as argument.
  • This search function basically takes an element and decides, whether it is the one you search for, or not aka it returns a boolean.
  • In my example the arrow function is c => c.aName === 'AssignmentName1', which is shorter and easier to read than a normal function definition. (You can call c whatever you want, it's just cleaner this way.)
  • You can exchange find() with filter(), if you accept multiple results and not just the first one.

CodePudding user response:

You first have to parse the JSON string:

const parsedJSON = JSON.parse(jsonString);

The object returned is contains all the data from your JSON string. To access the assignments array you can use dot notation.

const assignments = parsedJSON.assignments;

If you don't need to support old browsers, ES6 has a handy function for finding the value in an object. Use the "find"-function and pass a function that returns true for the item you are looking for:

const selectedAssignment = assignments.find( (assignment)=> {
  return assignment.aName=="AssignmentName2";
});

If you don't want to use ES6 you can use a for loop.

var assignments = JSON.parse(jsonString).assignments;
function getAssignmentWithName(name) {
  for (var i = 0; i < assignments.length; i  ) {
    if (assignments[i].aName == name) {
      return assignments[i];
    }
  }
  return false;
}
var selectedAssignment = getAssignmentWithName("AssignmentName1");
  • Related