tips for accessing dynamic key pair value data in Angular

I am facing an issue where I cannot retrieve the dynamic key pair value from the dynamic JSON. Below is my JSON:

var d =   {
      "pexels-photo.jpeg": {
        "information": "laptop",
        "desc": {
          "mimetype": "image/jpeg",
          "id": "shsj44",
          "file_id": "pexels-photo.jpeg"
        },
        "_id": "shsj44"
      }
    }

Here, I have attempted the following:

Object.keys(d).forEach(function(key){
    var value = d[key];
     console.log(key + ':' + value) ;
});

I am looking to extract the values of the id "_id" and "file_id".

Answer №1

To implement Destructuring assignment in JavaScript, follow this example:

var data = {"dynamic": {"info": "laptop","details": { "mimetype": "image/jpeg","id": "shsj44","file_id": "pexels-photo.jpeg" },"_id": "shsj44"}}
 
let dynamicKey = Object.keys(data)[0]
let {[dynamicKey]:{details:{
  file_id
},_id}} = data

console.log(file_id, '\n', _id)

Answer №2

Explaining the reason for the issue, when using the + sign before the value, it tries to concatenate the value resulting in [object object]

var d = {
  "pexels-photo.jpeg": {
    "information": "laptop",
    "desc": {
      "mimetype": "image/jpeg",
      "id": "shsj44",
      "file_id": "pexels-photo.jpeg"
    },
    "_id": "shsj44"
  }
}


Object.keys(d).forEach(function(key) {
  let value = d[key];
  console.log(key + ' : ', value);
  console.log(key + ' : ', value.desc.id);
});

Answer №3

To determine if the value is an object, it's important to check first. If it is indeed an object, then looping over it again becomes necessary.

The code below will display each key-value pair in the variable d

export class AppComponent implements OnInit {
  d = {
    'pexels-photo.jpeg': {
      'information': 'laptop',
      'desc': {
        'mimetype': 'image/jpeg',
        'id': 'shsj44',
        'file_id': 'pexels-photo.jpeg'
      },
      '_id': 'shsj44'
    }
  };

  ngOnInit(): void {
    this.iterateObject(this.d);
  }

  iterateObject(value) {
    Object.keys(value).forEach(key => {
      const newValue = value[key];
      if (typeof (newValue) === 'object') {
        this.iterateObject(newValue);
      } else {
        console.log(key + ':' + newValue);
      }
    });
  }

}

Answer №4

Check out this code snippet:

var data = {
      "pexels-photo.jpeg": {
        "information": "laptop",
        "desc": {
          "mimetype": "image/jpeg",
          "id": "shsj44",
          "file_id": "pexels-photo.jpeg"
        },
        "_id": "shsj44"
      }
    };
    
Object.keys(data).filter(key => {
    Object.keys(data[key]).filter(item => {
        if (item === 'desc') {
        Object.keys(data[key][item]).filter(elem => {
            if ((elem === 'id') || (elem === 'file_id')) {
              console.log(elem + ' : ' + data[key][item][elem]);
            }
          });
        }
      })
});

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

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

Node.js/Express API Endpoint Ceases Functioning

In my Angular/Express.js app, there is a post method within my api.service.ts file: post(data: any, endpointUrl: string): Observable<T> { console.log("REACHED POST METHOD") return this.http.post<T>(`${this.apiUrl}/${endpoint ...

I am currently focusing on using websockets in combination with JavaScript and Golang servers to efficiently transmit files and

When front-end JavaScript websockets send a JSON object, it looks something like this: message_type: "1" to: "umesh" from: "moin" body: "" file: "{"filename":"reportesmtp.pdf" ,"fileextension":"application/pdf" ,"filesize":61813 ,"filedata ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

jQuery functions failing to target dynamically generated elements

I've encountered an issue while attempting to implement my jQuery functions on dynamically created content using the .on API from jQuery. The main objective of the code is to display a specific set of options only when a user hovers over the ".feed_po ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive: { "listCustomFields": [ { "configurationType": null, "errorDetails": null, "fieldId" ...

Animating a 3D object along a path in Three.js

I am trying to shoot a projectile from one mesh to another. I connected them with a line, but now I'm struggling to move the projectile along this path. The translateOnAxis function didn't seem to do the job. Do you have any suggestions for how ...

Struggling to find your way around the header on my website? Let me give

I'm looking to display certain links prominently at the top of a page, similar to this example: "home > page1 > link1 > article 1." Can someone advise on how to achieve this using HTML, PHP, or jQuery? ...

Create a full type by combining intersecting types

I have multiple complex types that are composed of various intersecting types. I am looking to extract these types into their final compiled form, as it would be useful for determining the best way to refactor them. For example, consider the following: ty ...

Modifying a group of Components in Angular using a Service

Managing a set of Components involves changing their properties using a Service. The Components have a minimal model and are meant to remain compact. They are being rendered with *ngFor. The Service possesses a large Object and should possess the abilit ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){ $("#items").children().click(function(){ $(this).toggleClass('clicked'); }); }); .clicked { background-color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></s ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Throw a specific exception pointing to the location of invalid JSON data without cluttering your code with excessive try/catch

Dealing with a complex JSON object containing various settings can be challenging. Here's an example structure: { "configuration" : { "name": "<room name>", "players": {"min": 3, &quo ...

Having trouble retrieving the value of a custom directive attribute

My custom directive, named "mycomponent", has the following configuration: restrict: 'AE', templateUrl: 'template.html', scope:{ sTransactionType: '=transactionType', sStorageVariable: '=storageVariable&apos ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

Unlocking the Power of Hash Values in Ruby

Looking to extract JSON data and create a custom dictionary displaying a subset of the information. The challenge is that the input data varies depending on what is scanned using nmap. Some elements may be presented as an array value, while others may not. ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Error encountered while executing ExpressJs function that was converted to a promise

Understanding how errors are handled in promises can be a bit tricky, especially for someone new to promises like myself. I'm trying to make the most of them, but I'm not quite there yet. Here is the code snippet I'm working with: app.list ...