Discover the dynamic method for determining the value of a nested array based on a specific condition

Currently, I am delving into the world of nested arrays and attempting to locate a specific value within the array based on a condition. The data returned by the API is structured in the following format:

data=
  {
    "ch_Id": "1234",
    "title": "Title",
    "status": 4,
    "options": [
      {
        "ch_message": "ABC broad casting ",
        "ch_title": "ABC",
        "referenceType": "Internal"
      }
    ],
    "stage": "active"
  }

I am focused on dynamically loading data into a div depending on a certain condition. This means that sometimes the fieldname will be 'ch-Id', and other times it will be 'options[0].ch_message'. How can I programmatically retrieve the value of the fieldname, regardless of what is supplied as input, and bind it to the div?

For 'ch_Id', I understand that I can obtain the value using 'data[ch_Id]', however, when I attempt 'data[options[0].ch_message]', I receive 'undefined'.

displayValue: any;

constructor() { }

ngOnInit(): void {

this.fieldName = resultData[fieldName]; // this could either be ch_Id or options[0].ch_message

// Filter the array value based on fieldName
const filteredData = Object.entries(this.data).filter(([key, value]) => key === this.fieldName)
this.displayValue = filteredData[0][1]
console.log('this.displayValue',this.displayValue);

}

Answer №1

I found the solution I was looking for in the code provided by Nick Grealy at this link.

Accessing nested JavaScript objects and arrays by string path

const deep_value = (obj, path) => 
path
    .replace(/\[|\]\.?/g, '.')
    .split('.')
    .filter(s => s)
    .reduce((acc, val) => acc && acc[val], obj);


console.log(deep_value(someObject, "part1.name"));               
console.log(deep_value(someObject, "pa[rt3[0].name")); 

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 are the best methods for looping through ids in MongoDB and executing actions on them?

I am working with an entity object that has the following response: [ { "public": false, "_id": "5eb6da3635b1e83", "createdAt": "2020-05-09T16:28:38.493Z", "updatedA ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

Tips for verifying the "truthiness" of an object, removing any falsy values, and making changes to the object

I am faced with the task of examining each property of an object to determine if it is truthy, and then removing any that are not. var user = { name: 'my name', email: null, pwHash: 'U+Ldlngx2BYQk', birthday: undefined, username: &ap ...

Unable to display JSON results in a tabular format

After successfully implementing the AJAX method in jQuery, I am able to receive a response. However, I am encountering difficulties when trying to display the arrays in a table format. success:function(resp){ var json =JSON.parse(JSON.stringif ...

Tips for utilizing the nth-child selector to exclude hidden divs

I am facing an issue with displaying random blocks in rows. Each time a block falls into a new row, I want it to have a different style. However, when the user clicks on a button to hide certain blocks using display:none, the problem arises because the nth ...

Array of arrays implemented in JavaScript

I'm working with a JavaScript array that contains string arrays: array1, array2, array3. I need to break this array down and access the individual arrays. What is the best way to achieve this? ...

Spacing issues while utilizing the <textarea> element

<tr> <td> <b>Escalation: </td></b> <td> <TextArea name='escalation' onKeyDown=\"limitText(this.form.escalation,this.form.countdown,100);\" onKeyUp=\"limitText ...

Using Websockets in combination with AngularJS and Asp.net

While working on my application that uses AngularJS with Websocket, I encountered a specific issue. The WebSocket communication with the server works fine as users navigate through different pages in Angular. However, when a user decides to refresh the p ...

What is the best way to store the contents of a .mat file in memory using MATLAB?

Is there a way to obtain the byte array of a specific matrix stored in a .mat file without saving it on disk? I usually save a matrix onto the disk using this command: save('a.mat', 'a') However, now I am looking for a method to keep ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Adding bootsprap css-4 to an Angular Java project using Maven

I have developed an Angular application with a Java-Spring backend framework. I have successfully built both the frontend and backend using Maven. To build the Angular application, I utilized the frontend-maven-plugin and installed Bootstrap 4 by running: ...

Display identical elements from an array and shuffle them every 300 seconds

I created this code snippet that currently displays 5 random rows of data from an array each time it is executed. My goal is to modify the code so that it selects and displays the same 5 random values from the array for a duration of 5 minutes before rand ...

Argument not accepted in JavaScript

Currently, I am encountering a unique error message while working with a complex function that iterates through elements in my JavaScript onSuccess event. The error I am seeing is: exception encountered : {"message": "Invalid argument.", "description": " ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

Exploring the depths of Nesting in Next.js Links

After trying to nest the Badge inside the Link element and wrapping it in an <a> tag, I managed to resolve some errors but one persists: https://i.sstatic.net/o1WfA.png import { useState } from 'react'; import Link from 'next/link&apo ...

Debating the use of cameras in Three.js

Creating a camera in code typically looks like this: var camera = new THREE.PerspectiveCamera( FOV, ASPECT_RATIO, NEAR_PLANE, FAR_PLANE ); But what exactly do these values represent? ...

Leveraging the capabilities of the Swagger-generated Angular API client library for efficiently posting data in Angular 11

Trying to utilize the Angular API client library generated by Swagger from in Angular 11 has been successful for making API calls to retrieve results. However, the challenge lies in figuring out how to submit form data to the library. Any guidance or assi ...

Tips for retrieving input data sent from the parent component in Angular 2

I am working on a playlist component that receives an input 'playlist' from its parent component. This input is an object of arrays structured as follows: playList: { headerPlaylists: Array<any>, bodyPlaylists: Array<any> ...

Is it possible to ensure a div occupies all available space within a column using the vh-100 class in bootstrap?

In the <div class="bg-primary"></div> element, I'm trying to make it take up the remaining empty space without exceeding the vh-100. I've experimented with various solutions but haven't been able to find a fix yet. b ...