-2

I am making an application in Angular. I Have a Json file. How get all 'name' values in the array? Let's say that at the output I could get something like:

['Sony', 'Apple', 'Sony']

Json:

[
  {
    "Data": [
        {
            "name": "Sony",
            "color": "black"
        }            
    ] 
},
{
    "Data": [
        {
            "name": "Apple",
            "color": "white"
        }            
    ] 
},
{
    "Data": [
        {
            "name": "Sony",
            "color": "red"
        }            
    ] 
  }
]

app.component:

import { Component, OnInit } from '@angular/core';
import resData from '../assets/result.json';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.pug',
 styleUrls: ['./app.component.styl']
})

export class AppComponent {
 tasks: any = resData;   
 console.log(this.tasks); //While displaying just array
}
Kroshandowski
  • 81
  • 1
  • 8

2 Answers2

1

you can use map function for this.

let names = arr.map(element=> element.Data[0].name);

Note in here i assumed Data has only one instance.

let arr = [
      {
        "Data": [
          {
            "name": "Sony",
            "color": "black"
          }
        ]
      },
      {
        "Data": [
          {
            "name": "Apple",
            "color": "white"
          }
        ]
      },
      {
        "Data": [
          {
            "name": "Sony",
            "color": "red"
          }
        ]
      }
    ]
    
    let names = arr.map(element=> element.Data[0].name);
    console.log(names);
0

Use below code

 let x = [
            {
                "name": "Sony",
                "color": "black"
            }, 
            {
                "name": "Apple",
                "color": "white"
            },   
            {
                "name": "Sony",
                "color": "red"
            },
            {
              "name": "Sony",
              "color": "black"
          }, 
          {
              "name": "Apple",
              "color": "white"
          }  
              
    ];
    let output:any = [];
    let allNames = [];
    let uniqueNames = [];
x.forEach(element => {
  let index = output.findIndex(status => status.name === element.name);
  if(index>=0){
    let obj = output[index];
    obj.count = obj.count+1
    output[index]= obj;
  }else{
    output.push({name:element.name,count:1});
    uniqueNames.push(element.name);
  }

  allNames.push(element.name);
});
console.log(allNames);
console.log(uniqueNames);
console.log(output);
surendra kumar
  • 1,686
  • 11
  • 15