Richard
Richard

Reputation: 171

Parsing JSON items using Angular

I have a JSON object and I want to give the values of the properties to 4 of my variables using Angular, which are the following:

authorText : string;
titleText : string;
durationText : string;
genreText : string;

And here is the JSON:

"{"n":{  
   "_id":1101,
   "labels":[  
      "Song"
   ],
   "properties":{  
      "duration":"214000",
      "author":"Shawn Mendes",
      "genre":"pop",
      "title":"In My Blood"
   }
}
}"

I tried using this and similar solutions to this:

Object.keys(editData).forEach(function (key) {
  console.log(key);
  if(key === "author"){
     this.authorText = editData[key];
  }
  console.log( key , editData[key] );
});

But the key is always 0 for some reason.

EDIT Added the image of the JSON: The string I printed before was done as following : Saving it as global variable and then using JSON.stringify(temp1);.

enter image description here

Upvotes: 1

Views: 50

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

You can use this:

const { duration, author, genre, title } = this.editData[0].n.properties;
this.song = {
    authorText: author,
    titleText: title,
    durationText: duration,
    genreText: genre
};

Here, we're destructuring the properties from the properties key and just assigning them to the song Object's keys one by one.


A better thing to do would be just to name the fields as duration, author, genre, and title. Then you can simply do something like this:

export interface Song {
  author: string;
  title: string;
  duration: string;
  genre: string;
}

And in your function:

this.song = { ...editData[0].n.properties };

Here, we're using the spread operator(...) to spread the properties object's keys and assign them to the song property on your Component Class.


Here's a Sample StackBlitz for your ref.

Upvotes: 2

DeborahK
DeborahK

Reputation: 60518

You can just do this:

this.song = this.editData.n.properties;

I have a stackblitz demonstrating it here: https://stackblitz.com/edit/angular-udmdqr

The basic code is here:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Hello {{song.author}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  song: Song;
  editData = {
    "n": {
      "_id": 1101,
      "labels": [
        "Song"
      ],
      "properties": {
        "duration": "214000",
        "author": "Shawn Mendes",
        "genre": "pop",
        "title": "In My Blood"
      }
    }
  }

  constructor() {
    this.song = this.editData.n.properties;
  }
}

export interface Song {
  duration: string;
  author: string;
  genre: string;
  title: string
}

Upvotes: 1

Related Questions