JSON manipulation using JavaScript

Looking to dynamically choose a JSON key directly from the JSON Object.

var text = 
    '{"employees":[' + '{"firstName":"lastName", "lastName":"Doe" }]}';  

var obj = JSON.parse(text);
var firstName = obj.employees[0].firstName;
var lName = obj.employees[0].firstName;

document.getElementById("demo").innerHTML =
     firstName + " " + obj.employees[0].lName;
  
<div id="demo"></div>

Result Received: "lastName undefined".

Expected Result: "lastName Doe"

Answer №1

To implement the required changes, modify the code as shown below:

var jsonData = '{"employees":[' +
'{"firstName":"John","lastName":"Doe"}]}';

var obj = JSON.parse(jsonData);
var firstName = obj.employees[0].firstName;
var lastName = obj.employees[0].lastName;
document.getElementById("demo").innerHTML =
firstName + " " + lastName;

You can view the updated code in action here:http://jsfiddle.net/NJMyD/5349/

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

Could there be a glitch in Chrome? Tweaking the CSS on the left side

Take a look at this jsfiddle where I modified the left CSS property by appending "px" to it: function adjustLeft(leftVal) { var left = parseFloat(leftVal); //tooltip.style.left=left; tooltip.style.left=left + "px"; log("left: " + left + ", ...

Transform HTML into PNG with Canvas2image, followed by the conversion of PNG into BMP

Is there a direct way to convert HTML to BMP? After searching online, it seems that there isn't a straightforward method. So, I decided to convert HTML to PNG using canvas JS and then use PHP to convert the file from PNG to BMP. I have a question abou ...

The MongoDB query isn't functioning properly as the Match operation is returning an array with no elements

I am currently facing an issue with creating an aggregation pipeline. Everything seems to be working fine in the code until it reaches the $match section, which returns nothing. Here is the snippet of my code: var userId = req.params.UserId const m ...

Rotation of objects using Three.js on a spherical surface

I have successfully implemented a particle system to evenly distribute points on a sphere and then place instances of a given geometry on those points. Now, I am looking to rotate those geometries to match the surface angle of the sphere. Below is the cur ...

Struggling with validating props in React with JavaScript

Hello everyone, I'm new to JS and react so please bear with me. I've encountered an issue in the CurrentNumber component where instead of getting a number type returned, it shows [object Object]. I believe there might be a problem with my types/p ...

The UNHANDLEDREJECTION callback was triggered prematurely during asynchronous parallel execution

Asynchronously using parallel to retrieve data from the database in parallel. Upon each task returning the data, it is stored in a local object. In index.js, the cacheService.js is called. Inside cacheService.js, data is loaded from both MySQL and MongoDB ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

Tips for executing flushall just once across various clusters with Node.js and Redis

Whenever my server starts up, I find myself needing to clear out the Redis memory. However, each time a new cluster is formed, it triggers a flushall command that wipes out everything in memory. Is there a way to only run flushall once on the very first se ...

I would like to find the difference between two arrays by creating a third array that only contains the elements not found in the first array

Subtracting elements from two arrays. arr1=["AT","IN","UK","US"] and arr2=["UK","ZA"]. I want the result to be arr1-arr2 = ["AT","IN","US"] I have attempted to perform the subtraction of the arrays as described above, but instead of obtaining the correct ...

Issue identified: Multer is unable to read the path property of req.file as it is undefined

I recently started working with node.js and wanted to create a simple REST Api with the ability to upload files. I decided to use multer from npm for file uploading and POSTMAN to send post requests. However, I encountered an error when trying to upload a ...

Retrieve JSON responses in a detailed manner without using any identifier references, always referring to specific instances

Here are the objects I am dealing with: public class X { private String id; private String name; private List <Y> ys; } @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Y { priv ...

After refreshing the page, users are redirected back to the login page

On my website, I created a main page and an index.html page that redirects to the main page through a login panel. The issue I am encountering is that when I log in successfully on the main page and then refresh the page, it takes me back to the login pag ...

Utilizing $setViewValue in Angular 1.4 for Input Date Fields

When using a basic input date field: <form name="form"> <input type="date" name="startDate" my-directive......... To unit test the corresponding myDirective, I am injecting values into the input using $setViewValue. I have decided to use $ ...

Unique text: "Custom sorting of JavaScript objects in AngularJS using a special JavaScript order

I'm working with an array structured like this: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = { start: '10:00', end: '11:30' } var item3 = { start: '12:00& ...

Launching an external JavaScript from within a separate JavaScript file

I'm in the process of developing a virtual 'directory' for various locations in my city to assist fellow students. Here's the concept: On a map, I've pinned all the locations Clicking on these pins triggers a JavaScript funct ...

Is it possible to conceal specific sections of a timeline depending on the current slide in view?

For my product tour, I've structured a timeline with 4 main sections, each containing 4-5 subsections. Here's how it looks: <ul class="slideshow-timeline"> <li class="active-target-main main-section"><a href="#target">Targe ...

Configure your restify REST API server to handle both HTTPS and HTTP protocols

I'm currently utilizing node.js restify version 4.0.3 The code snippet below functions as a basic REST API server supporting HTTP requests. An example of an API call is var restify = require('restify'); var server = restify.createServer( ...

Combine the click event and onkeydown event within a single function

I have a function that sends a message when the Enter key is pressed. However, I also created a button to send a message, but when I call this function, the message doesn't send, even though I added a click event. function inputKeyDown(event, input ...

Removing entered text from a Vuetify V-autocomplete once a selection has been made from the dropdown menu

One issue I'm encountering involves a v-autocomplete field with a drop-down list of items. It allows for multiple selections. <v-autocomplete v-model="defendantCode" label="Defendant Code" :items="defendantCodeOptions" ...

Error encountered while creating JSON tree causing StackOverflowError

Building an online store and in need of generating JSON to represent the category tree. However, encountering a StackOverflowError while generating it. Category Entity : @OneToMany @JoinColumn(name = "parent_category_id") private List<Category> subc ...