Ways to extract data from a JSON object

When using my web application, the Web API responds with the following JSON object:

[ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

My task is to extract the Body value from each JSON node by providing the corresponding templateID. The challenge lies in the presence of \r\n characters within the JSON data. Regardless, I must retrieve the Body value for each node. For instance, if I input 1, I should receive sample date hete hee. Name, and for 2, I require you soon.. How can this be achieved?

I have attempted a solution, but it does not seem to work as expected.

var data2 = [ 
   { 
      "templateID":1,
      "template":"{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
   },
   { 
      "templateID":2,
      "template":"{ \"Body\": \"you soon.\" }"
   }
]

function usersBasedOnIDs(isShow,field){

    var filtered=data2.filter(function(item){
        return item[field] == isShow;         
    });
    console.log(filtered);
}

usersBasedOnIDs(1,'templateID');

Answer №1

item[field] == isShow;  

You're lacking an object that meets this condition, it appears you wish to filter elements based on ID and then examine their body value.

var data2 = [{
    "templateID": 1,
    "template": "{\r\n  \"Body\": \"sample date hete hee. Name\"\r\n}"
  },
  {
    "templateID": 2,
    "template": "{ \"Body\": \"you soon.\" }"
  }
]

function fetchUsersBasedOnIDs(isShow, field) {

  var filteredData = data2.filter(function(item) {
    return item[field] == isShow;
  });
  console.log(filteredData && JSON.parse(filteredData[0].template).Body);
}

fetchUsersBasedOnIDs(1, 'templateID');

Answer №2

To discover the solution, you can follow these instructions:

let array = [ 
   { 
      "number":1,
      "content":"{\r\n  \"Body\": \"Enter sample text here. Name\"\r\n}"
   },
   { 
      "number":2,
      "content":"{ \"Body\": \"Expect a response soon.\" }"
   }
]
for(let i=0;i<array.length;i++){
  let item = array[i].content;
  console.log(JSON.parse(item).Body);
}

Answer №3

function retrieveUsersByTemplateID(templateID) {
    let foundUser = data2.find(function(user) {
        return user.templateId === templateID;
    });
    if(foundUser === undefined) {
        return;
    } else {
        return JSON.parse(foundUser.template).Body;
    }
}

console.log(retrieveUsersByTemplateID(1));

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

Sending data through props to components that can only be accessed through specific routes

File for Router Configuration import DomainAction from './components/domainaction/DomainAction.vue' ... { path: '/domainaction' , component: DomainAction }, ... Linking to Routes using Router Links ... <router-link to="/domainact ...

Understanding the scope within a .when .done function in jQuery

I'm currently grappling with accessing a variable from within a .when.done function. Take a look at this illustrative example: var colviews = { 1: true, 2: true, 3: false } $.when( $.getScript( "/mckinney_images/jquery.tablesorter. ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

Error encountered while parsing JSON data for a particular string

Seeking a solution: Presenting my data: {Path:5984fcb4-8bf8-4205-86f8-e6e2042ba610.jpg,StatusCode:OK} Unable to convert the string to Json using the method below: var obj = $.parseJSON(data); This website also states that my json is not formatted corr ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

Tips for achieving equivalent value from two separate arrays with the help of Lodash

I have two separate JSON array objects provided below. My goal is to extract the matching "stdname" value from the "stdcontinfo" JSON array and append it to the respective element in the "stdJson" JSON array. Is there anyone who can assist me in resolving ...

Using jQuery to animate a div within a PHP echo statement

<li> <a id="collection" href="collections.php"> <span class="glyphicon glyphicon-th white"> Collections</span> </a> </li> <?php include "pagination.php" ?> <script> $("#collection").clic ...

JQuery WCF Service is returning a 400 Bad Request response

I developed a WCF web service in ASP.NET 4.5 using VS2012 that delivers a JSON response successfully via the built-in webservice client. The endpoints are correctly configured in the Web.config file. However, I encountered an issue on the client side with ...

Retrieve main page elements from an additional page called PageSlide

I have implemented the jquery PageSlide plugin as a menu feature on my website. The plugin opens a separate page on the side of the main page to function as a menu. However, I am facing a challenge in accessing the main page's elements from this side ...

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

The React context is currently yielding an undefined value

I am puzzled by this issue. I have double-checked to ensure that the states value is not undefined, and it isn't. However, I am unable to pinpoint where I may be making a mistake. Here is my authContext.js file: const initialState = { isAuthorized: ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Managing arrays effectively within ngrx store

I'm currently utilizing ngrx/store in my application and encountering a challenge when attempting to save an array. To start, I initialize my array as empty with the following code: export interface AppState{ customObjects: Array<CustomObject& ...

How can I utilize JSON data to retrieve information using D3 library?

Currently, I am experimenting with learning D3 JS and endeavoring to create a bar chart using real-time data fetched from the openweather API. My aim is to display the City Name along with its corresponding temperature at the time of the query. However, a ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...