sison kk
sison kk

Reputation: 79

Fetch inner object array from object array - javascript

I have a nested object array like below,

data = [
  {
    "field": "A",
    "items": [
      {
        "Id": 001,
        "ItemDescription": "item 1"
      }
    ]
  },
  {
    "field": "A",
    "items": [
      {
        "Id": 002,
        "ItemDescription": "item 2"
      },
      {
        "Id": 003,
        "ItemDescription": "item 3"
      },
      {
        "Id": 004,
        "ItemDescription": "item 4"
      }
    ]
  }
]

I am trying to fetch only the inner object array from the object array.

I have tried different ways to fetch the inner object array from object array,

data.map((u,i) => u[i].map((a,b)=> a.items))

expected result:

data = [
      {
        "Id": 001,
        "ItemDescription": "item 1"
      },
      {
        "Id": 002,
        "ItemDescription": "item 2"
      },
      {
        "Id": 003,
        "ItemDescription": "item 3"
      },
      {
        "Id": 004,
        "ItemDescription": "item 4"
    
      }
    ]

enter image description here

Upvotes: 0

Views: 77

Answers (2)

Rajdeep D
Rajdeep D

Reputation: 3910

You can use map and flat

let data = [
  {
    "field": "A",
    "items": [
      {
        "Id": 001,
        "ItemDescription": "item 1"
      }
    ]
  },
  {
    "field": "A",
    "items": [
      {
        "Id": 002,
        "ItemDescription": "item 2"
      },
      {
        "Id": 003,
        "ItemDescription": "item 3"
      },
      {
        "Id": 004,
        "ItemDescription": "item 4"
      }
    ]
  }
]

let result = data.map(d => d.items).flat();

console.log(result);

Output enter image description here

Upvotes: 3

M.Hassan Nasir
M.Hassan Nasir

Reputation: 851

Just use a single .map to get the values in the items array

let newArr = data.map((u,i) => u.items)
console.log(newArr)

and to return all the values in one single array use .flat

console.log(newArr.flat())

Upvotes: 1

Related Questions