0

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

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

11 Comments

Negative. Not matching my expected result. above code resulting me below json array. [ [ { "Id": 001, "ItemDescription": "eeeee" } ], [ { "Id": 002, "ItemDescription": "23434" }, { "Id": 003, "ItemDescription": "12342" }, { "Id": 004, "ItemDescription": "type B" } ] ]
It should work. Please check the codepen output in console. codepen.io/debraj1983/pen/YzZadRr?editors=0010
expected result is already mentioned in the question itself. I need the items 001 to 004 in a single array object.
meta.stackoverflow.com/a/356679/14032355 , you can just leave your js code in the code snippet
@ikhvjs This is amazing. Thank you.
|
1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.