Retrieving a data value using a specific key within a JavaScript object

Trying to retrieve a specific value by providing the literal key in a JavaScript object. The image below indicates that "filter" is equal to "Approved", sourced from reimb_status_description.

Line 6 of code assigns filter to the value.

const filter = Object.values(jsonData[i]["reimb_status_description"]).join("");

I am confused because without .join(""), filter would be "A,p,p,r,o,v,e,d" as an array of letters. Can someone explain why it becomes an array instead of just a string? Also, is there a more efficient way to extract the desired data?

https://i.sstatic.net/s5S3N.png

function PopulateReimbursementTable(jsonData, appliedFilter)
{
    ClearReimbursementTable();

    for(var i = 0; i < jsonData.length; i++)
    {
        const tr = document.createElement("tr");
        const entries = Object.entries(jsonData[i])

        const filter = Object.values(jsonData[i]["reimb_status_description"]).join("");
        console.log("filter: " + filter)
        for(const [key, property] of entries)
        {
            if(fields.includes(key)){
                console.log(key + "\t" + property);
                const td = document.createElement("td");
                if(key == "reimb_date_submitted" || key == "reimb_date_resolved"){
                    if(property == null)
                    {
                        td.innerHTML = "tbd";
                    }else{
                        var d = new Date(property);
                        let formatted_date = appendLeadingZeroes((d.getMonth() + 1)) + "-" + appendLeadingZeroes(d.getDate()) + "-" + d.getFullYear();
                        //console.log(formatted_date)
                        td.innerHTML = formatted_date;
                    }
                } else if(key == 'reimb_amount'){
                    if(property === null || property === undefined)
                    {
                        td.innerHTML = "tbd";
                    }else{
                        td.innerHTML = formatter.format(property);
                    }   
                }
                else
                {
                    if(property === null || property === undefined)
                    {
                        td.innerHTML = "tbd";
                    }else{
                        td.innerHTML = property;
                    }               
                }

                if(fields.includes(key))
                {
                    tr.appendChild(td);
                }
            }

        }

        if(appliedFilter == "All"){
            reimbTableBody.appendChild(tr);
        }
        else if(filter == appliedFilter){
            reimbTableBody.appendChild(tr);
        }
    }
}

Answer №1

When using the method Object.values with a String1, it retrieves the individual characters of the string as an array. In your scenario, you may access the string value by using

jsonData[i].reimb_status_description
.

1 This is because a string can be seen as a one-dimensional array consisting of character elements.

console.log(Object.values("some string"));

// this will give the original string
console.log(Object.values({someString: "some string"})[0]);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Answer №2

MDN documentation states:

The method Object.values() will provide an array containing the enumerable property values of a specified object

It has been observed that when using

jsonData[i]["reimb_status_description"]
, a string is returned. Any input passed to Object.values() is automatically converted into an object. In JavaScript, a string primitive can be transformed into an array-like object (more information here). Consequently, when passing a string to Object.values(), it gets converted into an array-like object where each character becomes an individual value within the resulting array.

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

What is the best way to prevent a form from being submitted and conduct validation using JavaScript?

Encountered a form that is unchangeable in appearance: <form id="mx_locator" name="mx_locator" method="post" action="search-results"> <!-- form elements --> <span><input type="image" src="/images/search.png" onclick="loader()"> ...

What is the best way to determine total revenue by consolidating data from various tables within an IndexedDB database?

Seeking guidance on building a stock/sales application in JavaScript with Dexie.js. I need assistance in efficiently calculating the Total Sales amount without resorting to overly complicated recursive code that triggers multiple queries for a single produ ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

What adjustments can I make to my jQuery code in order to animate the mobile menu when it is initially clicked?

I have been using the following mobile menu code for some time now and it has been working well. I have implemented a CSS animation so that when the menu button is clicked, it smoothly scrolls into view. However, I have noticed that the animation does not ...

Ways to pass properties while using render in reachrouterdomv6?

Currently, I am enrolled in a Udemy course, but the information provided is based on v5. I am struggling to understand the equivalent of "render" and how to pass props with it. Additionally, there seems to be an issue with the code - if the element is un ...

validate the existence of the username upon submission of the form

Here is some code that I have written. .js $(document).ready(function() { $("#username").focusout(function() { $.ajax({ type:'post', url:site_url()+'/client/checkUserName', data:{&apos ...

Searching for nested objects using dynamically generated property names

I am currently facing a challenge with accessing nested objects in MongoDb using the Node.js Driver, particularly when dealing with dynamic property names. Below is an example of my dilemma: //Although this code gives the desired results, it lacks dynamic ...

To Default or Not to Default: Dynamic Imports in React Router 3 for Webpack Code-Splitting

Lately, I've been focusing on upgrading my project from webpack 3 (v. 3.3.0) to webpack 4 (v. 4.44.2). Building and compiling went smoothly, but for some reason, nothing was being rendered on the screen. Upon comparing the parameters passed to Router ...

The TypeError encountered when using vue.js push arises from attempting to access the 'name' property of an undefined value

Here is a code snippet I am working with: new Vue({ el: '#core', data: { checkedThemes: [] ... } }) Afterwards, I have the following code: mounted() { ... var theme = parseInt(parameters['theme&apo ...

Angular with PHP Integration Success

I'm navigating the realms of Angular and PHP, understanding that Angular is client-side while PHP operates on the server. I'm curious if there's a way to merge these two technologies, as it's all quite unfamiliar territory for me. For ...

Converting a file from a URL to a blob in PHP for use in JavaScript

Attempting to convert an image from a URL to a blob file that can be utilized in JavaScript, but encountering challenges. Is this achievable and if so, how? Current attempts include: // $request->location is the url to the file in this case an ima ...

Transmitting and receiving a blob using JavaScript

Is there a way to send a blob using a JQuery ajax request and receive it server-side with Node.js + express? I tried sending the blob as a JSON string, but it doesn't seem to include any of the binary data: {"type":"audio/wav","size":344108} Are th ...

Animating numerous elements simultaneously during Vue component rendering

Take a look at this simple case in the following jsfiddle: https://jsfiddle.net/hsak2rdu/ I attempted to swap and animate two elements, but it didn't work as expected. When you click the toggle button in the playground, the second element quickly mo ...

The phenomenon of componentDidMount being triggered before the DOM is fully mounted arises when utilizing createPortal in React

I have written a React code snippet that looks like this: import React from 'react'; import ReactDOM from 'react-dom'; import ComponentB from './ComponentB'; class ComponentA extends React.Component { constructor(props) ...

Preventing Event Bubbling with Hammer.js 2.0: A Step-by-Step Guide

I have a situation with a parent and child div. I want to prevent panning or dragging on the child from affecting the parent. I came across a similar question that was asked a year ago, but I am using a newer version of Hammer.js with the jQuery wrapper. ...

Loading HTML and jQuery dynamically using AJAX

I am struggling to access a child element of HTML that is loaded dynamically through AJAX. Unfortunately, it's not working as expected. $.get('test.html', function(data) { var content = $('#content', data).html(); conso ...

Tips for creating a function to assign a CSS width using a JavaScript variable?

Here is the code snippet I have been working on: ...<script> function adjustElementSize() { var newSize = window.innerWidth - 600; document.getElementById("spin").style.width = newSize + "px"; document.getElementById("spin").style.height = newSize + ...

Modify the appearance of the datepicker and set the field to be view-only

As a beginner in jquery and the date picker, I'm struggling to change the date format to YYYY-MM-DD and restrict users from typing in the field, allowing only date selection. I have tried various methods without success. Any help or guidance would be ...

Which HTML element does each script correspond to?

Are there any methods to identify the script used in certain HTML elements? For instance, if I wish to determine the script responsible for creating a drop-down menu, I can locate the HTML and CSS for the menu but not the JavaScript (or other scripts). I ...

Utilizing the $scope variable within an event in the Google Maps API

I am having an issue using $scope within this function. Where should I define the argument $scope so that it works properly? Thank you Below is the basic structure of my code with key lines included: myApp.controller('myCtrl', ['$scope&ap ...