Having trouble accessing the value of an object within a nested array object

Looking for a way to extract the object value from a nested array object using JavaScript? If the sourcecountry matches the country in the object, it should return the corresponding payment service.

Here is what I have attempted:

function getValue(source, obj) {
      var list = obj.filter((cn) => {
         return cn.country_from.filter((c) => {
            return c.country == source;
         });
      });
}

var result = getValue(sourcecountry, obj);

var sourcecountry = "SG";
var obj = [
    {
     "country_from": [
            {
                "country": "SG",
                "payment_service": [
                    {
                        "type": "bank transfer",
                         "speed": {
                          "unit": "days",
                         "number": "2"
                     },
                    }
                ]
            },
            {
                "country": "TH",
                "payment_service": [
                    {
                        "type": "credit",
                         "speed": {
                          "unit": "days",
                          "number": "1"
                      },
                    }
                ]
            }
        ]
    },
]

Desired Output:

Speed: 2 Days

Answer №1

Here is a more streamlined version of the code provided. You only need one instance of .filter() instead of two. The outer one can be replaced with a .forEach().

var sourcecountry = "SG";
var obj = [{
  "country_from": [{
      "country": "SG",
      "payment_service": [{
        "type": "bank transfer",
        "speed": "2 days"
      }]
    },
    {
      "country": "TH",
      "payment_service": [{
        "type": "credit",
        "speed": "1 day"
      }]
    }
  ]
}];
var result = retrieveValue(sourcecountry, obj);
console.log(result);

function retrieveValue(source, ob) {
  var list;
  ob.forEach((cn) => {
    list = cn.country_from.filter((c) => {
      return c.country == source;
    });
  })
  return `Speed: ${list[0].payment_service[0].speed}`;
}

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

Ways to clear an individual form field using element-ui

I'm currently learning VueJS and incorporating the Element-UI framework into my project. One issue I'm facing is that when there's a validation error upon submitting the login form, I'd like to automatically clear the password field. A ...

Creating a sidebar navigation in HTML and CSS to easily navigate to specific sections on a webpage

Here's a visual representation of my question I'm interested in creating a feature where scrolling will display dots indicating the current position on the page, allowing users to click on them to navigate to specific sections. How can I achieve ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...

Two tags attached to four hypertext links

Within my HTML code, I have hyperlinks present on every line. However, I am seeking to eliminate these hyperlinks specifically from "your previous balance" and "your new balance".https://i.sstatic.net/ekVGT.png In the following HTML snippet: <tr *ngFor ...

Button click functionality for updating in Classic ASP is functioning correctly exclusively in Internet Explorer and not in other web browsers

Currently, I am in the process of enhancing a Classic ASP application. Within this application, there is an HTML table that is populated from a SQL database. One cell within the table contains checkboxes. Upon clicking one of these checkboxes, a popup wind ...

Leverage Next.js routing in plain JavaScript without relying on React hooks

I am working on a NextJS app and I need to implement a function that can redirect to any page using Next.js routing. For example, after a user completes the signup process, I want them to be redirected to a specific page. So, I tried creating a reusable ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

PointerLockControls maintains a constant speed without slowing down (threejs)

I have integrated THREE.PointerLockControls into my project following the implementation demonstrated in this example (view code). The code seems to be accurately translated from the example, but I am facing issues with deceleration of the controller once ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

"Exploring the depths of PHP: Generating a JSON string from an array

I am trying to work with PHP code in an Object-Oriented manner and the values I am getting are objects. However, I need to convert these O.O.P objects into JSON data for use by JavaScript. So, I converted my objects into arrays on the PHP end, but when I t ...

substituting the deep watcher in Angular

In my application, I am working with a data object called fulldata, which consists of an array of objects. fulldata = [ {'key': 'abc', values: {.....},....}, {'key': 'efg', values: ...

`Thoughts on Difficulty Attaching Child Elements in JavaScript with appendChild`

I am having trouble with appending some HTML that is being received as a string in a div. For some reason, the appendChild method is not working as expected. Here is my JavaScript code: var doc = document.getElementById("products"); var notes = doc.getEle ...

Having trouble submitting the edit form

I had the idea to create an edit form that would replace the existing data in a table for editing. However, I am facing issues with getting the form to submit properly even though the create form is functioning correctly. Below is the code snippet that I n ...

Using JavaScript Regular Expressions to locate all prefixes leading up to a specific character

Consider a scenario where you have a string consisting of terms separated by slashes ('/'), like this: ab/c/def Your goal is to identify all the prefixes of this string up to a slash or the end of the string. For the given example, the expected ...

Alter the background color of a React application with a single click in a spontaneous manner

When I attempted to change the background color of the entire page randomly by clicking a button, it only changed the background of the div element. Here is the code snippet I used: import React from "react"; class Home extends React.Component { ...

Error encounter in JSP is nested within another JSP file, both of which utilize jQuery

Before proceeding, it is important to note that I am in the process of selecting a month using a datepicker and a specific meter (by its serial number). Once this information is selected, a query will be sent to a MySQL database to retrieve data for plotti ...

Combining two asynchronous requests in AJAX

In the process of customizing the form-edit-account.php template, I have added ajax requests to enhance the functionality of the account settings form. The form allows users to modify their name, surname, age, and other details. While the ajax implementati ...

What is the best way to iterate through an object and display each item as <li></li> within another <li>?

After retrieving a specific object from an express endpoint and seeing it on the console, I need to figure out how to map it in order to display a jsx that resembles this <li>keys</li> : <li>values</li> For example: Company: DML ...

Inspecting the Ace Editor within the onbeforeunload event handler to confirm any modifications

I'm attempting to utilize the $(window).on('beforeunload', function(){}); and editor.session.getUndoManager().isClean(); functions within the ace editor to detect whether a user has made modifications to a document without clicking the submi ...

What is the best way to present an array in tabular form within a Laravel view?

Is there a way to format the arrays below into a table in Laravel? Here are some sample arrays: {"1":{"name":"Bajiya","quantity":2,"price":"34.00"},"2":{"name":"Gulha","quantity":2,"price":"3.00"}} {"1":{"name":"Bajiya","quantity":2,"price":"34.00"},"2": ...