Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract value of nested object array?

I'm trying to extract all links IDs of the object array shown below. This is how I was trying to get that:

const linkIDs = array
  .filter(d => d.links)
  .map(d => d.links)

But this gives me a nested array, which is not what I wanted.

[
  {
    "id: "1",
    "links": [
        {
            "id" : "Dn59y87PGhkJXpaiZ",
            "type" : "article"
        },
      {
            "id" : "PGhkJXDn59y87paiZ",
            "type" : "article"
        }
    ]
  },
  {
    "id: "2",
    "links": [
        {
            "id" : "GhkJXpaiZDn59y87P",
            "type" : "article"
        }
    ]
  },
  {
    "id": "3"
  }
]

So in this example I need the result

[ "Dn59y87PGhkJXpaiZ", "PGhkJXDn59y87paiZ", "GhkJXpaiZDn59y87P" ]
like image 230
user3142695 Avatar asked Sep 12 '25 04:09

user3142695


1 Answers

You can do like bellow, without using any other library.

var data = [
  {
    "id": "1",
    "links": [
        {
            "id" : "Dn59y87PGhkJXpaiZ",
            "type" : "article"
        },
       {
            "id" : "PGhkJXDn59y87paiZ",
            "type" : "article"
        }
    ]
  },
  {
    "id": "2",
    "links": [
        {
            "id" : "GhkJXpaiZDn59y87P",
            "type" : "article"
        }
    ]
  },
  {
    "id": "3"
  }
];

var result = data.filter(e => e.links)
                 .map(e => e.links.map(link => link.id))
                 .reduce((a, b) => a.concat(b), []);
                
console.log(result);
like image 124
Daniel Tran Avatar answered Sep 13 '25 19:09

Daniel Tran