Determine whether a particular value is absent from a JSON object

I am looking to verify the absence of a specific value in the given object by filtering an array of strings.

My goal is to determine if the values within the keys array are present in the JSON object I am iterating through. If any of the values are missing, I need to take another action, but only if the non-existent value (in resArray) is part of the keys array.

Access JSON here

This is what I have attempted:

var keys = [
    "total_kills",
    "total_deaths",
    "total_planted_bombs",
    "total_defused_bombs",
    "total_kills_knife",
    "total_kills_headshot",
    "total_wins_pistolround",
    "total_wins_map_de_dust2",
    "last_match_wins",
    "total_shots_fired",
    "total_shots_hit",
    "total_rounds_played",
    "total_kills_taser",
    "last_match_kills",
    "last_match_deaths",
    "total_kills_hegrenade",
  ];

  var resArray = stats.playerstats.stats;
  var statsArray = [];

  for (var i = 0; i < keys.length; i++) {
    for(var j = 0; j < resArray.length; j++){

        //if the value in keys array exists, do something
        if(resArray[j]["name"] === keys[i]){
         //do something
       }
       if(<value doesn't exist)>)
         //do something else.
    }
  }

Solution:

function contains(obj, key, value) {
        return obj.hasOwnProperty(key) && obj[key] === value;
      } 

      var resArray = stats.playerstats.stats;
      var statsArray = [];

      for (var i = 0; i < keys.length; i++) {

        resArray.some(function(found){

          if(contains(found, "name", keys[i])){

            statsArray.push(found);

          }

        });

        if(typeof statsArray[i] == 'undefined'){

          console.log("Not present in array: " + keys[i]);
          statsArray.push({"name": keys[i], "value": 'None'});

        }
      }

Appreciation to everyone who contributed to this discussion thread.

Answer №1

Your approach suggests that you're generating a new array based on the statistics and conditional existence of the provided keys. A convenient method to construct this array involves utilizing Array.prototype.map to iterate through your stats array. Subsequently, within each iteration's callback function, you can use the name property as an argument for keys.indexOf to verify if that specific name exists in your keys array.

var statsArray = stats.map(function(stat) {
  if (keys.indexOf(stat.name) > -1) {
    return stat;
  } else {
    return stat.name + ' not found.';
  }
});

This process will result in a new array that includes either the stat object or annotates its absence in the keys. Nonetheless, you have the flexibility to return any desired output, as long as it adheres to the structure of a valid array item.

Below is a functional demonstration using a snippet of your dataset (applicable to the original dataset as well):

// Code snippet here...

Answer №2

To achieve your desired outcome, leverage the power of array functions for an effective solution:

const playerData = database.players.stats;
const selectedMatches = playerData.filter(item => keys.includes(item.name));
const matchNames = selectedMatches.map(match => match.name);
const nonMatchedKeys = keys.filter(key => !matchNames.includes(key));

Afterwards, simply iterate through the selected matches and non-matched keys to perform your tasks accordingly.

Check out the code in action on this JSFiddle link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Ways to extract certain characters from each element in an array

I'm attempting to make the first four characters of each element in an array (specifically a list) bold, but I am only able to select entire strings: $("li").slice(0).css("font-weight", "Bold"); Is there a way for me to indicate which characters wit ...

When the overflow-y property is set to hidden, the page unexpectedly scrolls to the top in Firefox

I have a javascript code that is responsible for opening modal popups on my website. It also manipulates the overflow-y property of the <html> element by setting it to hidden. Interestingly, in Chrome and IE, this functionality works as intended. The ...

If no image is found within the container, include a default image

I am currently working on this project. My goal is to display a default image if there is no image in the post. The JQuery code I have implemented is: $(function () { $(".post").each(function () { var posthead = $(this).find("h2.post-title") ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

Tips for utilizing jsonSlurper() with conditional if/else statements in Groovy?

Currently, I am attempting to parse through a JSON file in order to retrieve the status associated with 'stop-emu'. def stageJson = new JsonSlurper().parseText(response?.content) stageJson.stages.each { echo(it) } //status = ???? The snippet of ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

Display the complete image once the loading process is finished on Angular 12

When retrieving image src via API from the server, I aim for the image to only be displayed once completely loaded. In the meantime, I would like a skeleton outline to be shown during the loading process (images are segmented into sections and the skeleton ...

JavaScript table supported by a REST API

Issue at hand: I am in search of a table component that seamlessly integrates with my web application. The challenge lies in connecting the existing REST endpoints to the table for data retrieval, whether it be paginated or not. Adjusting the endpoints t ...

Implementing a JavaScript function to trigger the 'GET' method upon page load repeatedly

I am facing a strange issue where a javascript function is running multiple times upon page load (7 times in Chrome, 3 times in IE, 7 times in Firefox, 6 times in Opera, 4 times in Safari, and 4 times in Edge). What's going on??? Moreover, the xmlHtt ...

Turn off PrettyPhoto functionality in the code base

Is there a way to deactivate PrettyPhoto once it has been activated? $(document).ready(function () { $("a[rel^='prettyPhoto']").prettyPhoto(); } $("#disablePrettyphoto").click(function (e) { $("a[rel^='prettyPhoto']").KILLPRET ...

What is the best way to input variables into json values? [JavaScript]

let countryCode; let countryName; $(window).on("load", function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" }).done(function (json) { countryCode = json.country_code; $(function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

The Facebook login button mysteriously vanishes when I hit the refresh button on Internet Explorer 9

Issues with the Facebook login button disappearing in Internet Explorer 9 after page refresh. All other browsers are functioning correctly, but IE only displays the button initially and then it disappears on any subsequent refresh. Utilizing Facebook conn ...

JavaScript Arrays with Four Dimensions

Looking for a solution to generate arrays with any number of dimensions, including 4D arrays. I'm interested in being able to use the function to create an array and then access it like this: arr[3][2][23][12] = "amazing"; ...

Exploring the world of JSON arrays in C#

Ways to interpret JSON data containing employee information in C#: { "empdata": { "emp": [ { "DATE": "07.01.2021", "EMP_ID": "A001", "S_DATE": "2021-01-07T00:00:00.000+00:00", "Desig": "Engg" }, { "DATE": "08.01.2021", "EMP_ID": "A002", "S_DATE": "2021-0 ...

finding the initial instance of a value surpassing a certain threshold in a numpy array

Consider a 2D array like the following: r1= np.array([[1,2,3,4],[2,3,4,5],[3,4,5,6]]) The task at hand is to identify, for each row, the first instance of a value greater than a predefined threshold. This can be achieved using the code snippet below: de ...

What is the best method for creating a top margin that is dependent on the height of the browser?

Is there a way to make the CSS margin: top; on my HTML main_content element relative to the browser window? I want the main_content to always stay at the bottom of the browser window. How can I achieve this? I attempted the following code, but it didn&apo ...