Ways to retrieve the value of an object based on its key name

I've exhausted all possible combinations such as x.y, x['y'], x.y.z, x['y'].z in an attempt to access the value of an object within an array using its key name. Despite my efforts, I'm unable to retrieve the desired value. The data returned from the SQL query is as follows:

parseMissionData:  {record: Array(1), code: 1}
    code: 1
    record: Array(1)
        0: alt: 45
        attribute: Array(6)
            0: {name: "messageCode", value: "10"}
            1: {name: "gpsFix", value: "2"}
            2: {name: "autonomous", value: "0"}
            3: {name: "lowBattery", value: "1"}
            4: {name: "intervalChange", value: "30"}
            5: {name: "resetDetected", value: "0"}
            length: 6
        __proto__: Array(0)
        azimuth: 0
        datetime: "2018-03-24T20:10:00.000Z"
        devid: "300434060496300"
        lat: 37.335394620895386
        lon: -121.82005405426025
        speed: 0
        __proto__: Object
            length: 1
        __proto__: Array(0)
        __proto__: Object
....

Since attributes might not be consistently ordered, assuming attribute[0] corresponds to 'messageCode' is not viable. My goal is to test the value of the 'messageCode' attribute and use it for further processing. Here are some attempts I've made:

response.record[i].attribute['messageCode']
response.record[i].attribute.message.value
response.record[i].attribute['messageCode'].value

Despite numerous iterations, I haven't been successful. Is there a direct method to access the 'messageCode' attribute without iterating through the array?

Update: Following Mathias247's suggestion, I revised the code:

function parseMissionData(response) {
    console.log('parseMissionData: ', response);
    var codeAttribute;
    for (var i=0; i < response.record.length; i++)
        codeAttribute = response.record[i].attribute.find(elem => elem.name == "messageCode");
        console.log('messageCode: ', codeAttribute);
        console.log('imei direct: ', response.record[i].devid);
}

The updated code allows me to retrieve the 'messageCode' value successfully, but unexpectedly, the reference to 'devid' (response.record[i].devid) has now broken and returns undefined! When I remove the find() function related to 'messageCode', the devid reference works again. I am perplexed by how referencing using find() can impact another reference that previously worked. Can someone help clarify this behavior?

messageCode:  {name: "messageCode", value: "10"}
jquery.min.js:2 jQuery.Deferred exception: Cannot read property 'devid' of undefined TypeError: Cannot read property 'devid' of undefined
     at parseMissionData (http://localhost:3000/js/controller.js:1036:67)
     at Object.<anonymous> (http://localhost:3000/js/controller.js:1021:17)
     at j (http://localhost:3000/js/jquery.min.js:2:29948)
     at k (http://localhost:3000/js/jquery.min.js:2:30262) undefined

To add more confusion, switching the order of console logs results in varying outcomes:

function parseMissionData(response) {
    console.log('parseMissionData: ', response);
    var codeAttribute;
    for (var i=0; i < response.record.length; i++)
    console.log('imei direct: ', response.record[i].devid);
    codeAttribute = response.record[i].attribute.find(elem => elem.name == "messageCode");
    console.log('messageCode: ', codeAttribute);
}

If I first log response.record[i].devid, it displays correctly, but then 'codeAttribute' throws an error stating 'Cannot read property 'attribute' of undefined'. Reversing the logs reveals similar issues with different references. Clearly, I'm missing something critical here. Any insights would be greatly appreciated.

Answer №1

Is it necessary for me to loop through the array attributes and find a match with the name value?

Absolutely, however, you have the option of utilizing the array prototype method find to easily locate the relevant entry. For instance:

let codeAttribute = response.record[i].attribute.find(elem => elem.name == "messageCode")
// codeAttribute.value === '10'

Answer №2

I simulated the issue you’re facing with a similar scenario and successfully retrieved the values for both "messageCode" and "devid". Please specify the exact cause of the problem:

alpha = {name: "messageCode", value: "10"}
beta = {name: "gpsFix", value: "2"}
charlie = {name: "autonomous", value: "0"}
delta = {name: "lowBattery", value: "1"}
echo = {name: "intervalChange", value: "30"}
foxtrot = {name: "resetDetected", value: "0"}

attributes = [alpha, beta, charlie, delta, echo, foxtrot]

data = { attributes, azimuth: '0', datetime: "2018-03-24T20:10:00.000Z", devid: "300434060496300", lat: '37.335394620895386'}
parseData = { data, code: 1}

console.log(parseData);

console.log(parseData.data.attributes.find(obj => obj.name === 'messageCode').value);
console.log(parseData.data.devid)

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

Guide on transferring information from the user interface to the server-side by utilizing AJAX and Django

INTRO: Currently, I am developing a Django application that requires the transfer of data from the front-end to a views.py file located in the back-end. I have implemented a button that initiates a transaction upon being clicked. This is how the button is ...

Determine the location of the button within an array of objects

I have designed a button symbol and exported it using Export for ActionScript with the class name "theButton". In my object, I want to instantiate this button in the constructor of myObj as shown below: public class myObj extends Sprite { private ...

Angular 2 TypeScript: The concat() function operates as mutable within the framework

When I declare an array on an @Injectable provider, my intention is to use it across different components. normeList: any[] = [ { name: 'choice 1', type:'false' }, { name: 'choice 2', typ ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

How to Utilize FormData in IE9 with Angular 5 and TypeScript Without Ajax or jQuery

Within my Angular 5/Typescript application, there is an UploadFile component structured as follows: component.html .... <form #formUpload id="formUpload"> <input type="file" class="input-file-ghost" (change)="onChangeFile($event.target.files) ...

"Trigger a click event on a DOM element whenever the component's props

I created a component with a click event in the componentDidMount lifecycle method. Each time the component is rendered, I want the div to be clickable. The issue I am facing is that the componentDidMount method runs only once, and the click event does n ...

Tips on uploading files to dropzone and sending them via an ajax request as though they were regular input file fields

I am looking to send files via formData in an ajax request and have the server interpret it as if it were coming from an input file field. I attempted a solution I found here: Add files from Dropzone to form However, when I make the request, the server d ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

There seems to be a delay in reading data when I switch a component from stateless to stateful

Initially, I had a stateless component that was reading data perfectly on time. However, when I needed to convert it into a stateful component for my requirements, it stopped functioning as expected. The component would display empty data and wouldn't ...

Which specific graphing library does GitHub utilize for its Graphs section?

Which graphing library is utilized by GitHub on its Graphs tab? The graphs displayed at https://github.com/USER/REPOSITORY/graphs/commit-activity are visually appealing, detailed, and adaptable. If they are leveraging an open source javascript library fo ...

How can you use window.open to open a URL and send information to it?

Is it possible to interact with a page opened using window.open() and pass data to it? For instance, can you input data into a text field on the opened page? Is it feasible to access elements on that page by their ID similar to using getElementById()? Ar ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Verifying if multiple elements within a row of a two-dimensional array share the same value

My challenge is with handling an array list whose size is determined by user-input variables and filled initially with zeros. As the program runs, different elements in the grid are updated to either ones or twos. It's a straightforward process up unt ...

When attempting to fetch data from Strapi v4 and display it in ReactJS, all that is shown is an empty array

I've encountered an issue while trying to map data from Strapi, as I'm getting an empty array. Surprisingly, the endpoint functions properly when tested on Postman: https://i.sstatic.net/4B4O7.png The custom useFetch function seems to be malfunc ...

initiate a new action when the type value is modified

For example, I start with a type like this: type wallPaper = 'red' After applying this type to 100 variables, I decide I want a different color: type wallpaper = 'blue' Is there an extension that can automatically replace the value ...

Mastering the Art of SQL Submission with PHP Ajax Requests

I've encountered an issue with a form that, upon validation, triggers two Ajax requests before submitting the data to create an entry in a MySQL database. The Ajax requests generate URLs to Google Documents using upload.php. However, when certain unk ...

Conceal the vacant area located at the top of the page

By clicking on the "Run code Snippet" button or visiting this link, you may notice a significant amount of empty space at the beginning of the page. The images only become visible once you start scrolling down. I am looking for a solution to hide this emp ...

Comparison between Release and Debug versions: encountering an unexpected runtime error

I am working on a program that utilizes an FFT on a 2D array. To use the fftw3 library, I need to employ a temporary array named FTtemp to store the results of the FFT. This array is in 3D as it holds values for the x and y axes, as well as real and imagin ...

What exactly is the task of the Angular compiler?

Someone asked me this question today and I couldn't come up with a proper response. When it comes to deploying, Typescript transpiles to JS and then there is tree shaking, "less" (optional), and various optimizations involved. However, is any of this ...

Issue with jQuery mouseenter() function not meeting expectations

My goal is to create a div that changes its size when hovered over (using the mouseenter and mouseleave jQuery functions) and shows another div when clicked. However, I am experiencing inconsistent behavior with my jQuery code. Here is the code I am using: ...