3

Does anybody know why this filterData map function is

returning an array of arrays instead of array of objects ?

I am using a map() function inside another map() so basically I am trying to iterate first map function over the big array and afterwards run it inside the child array.

I just want to return an simple object only wit the data that I select in the second map object.

function apiCall() {
    const promises = urls.map((url) => axios.get(url, { headers }));

    Promise.all(promises).then((responses) => {
      let data = [];
      let filterData;
      responses.forEach((response) => {
        data = data.concat(response.data);

        filterData = data.map((nested0) => 
          nested0.childNested.map((nested1) => {
            return {
              id: nested0.id,
              name: nested0.serve,
              date: nested1.name
            };
          })
        )
      });
    });
  }

and this is the json structure that I want to iterate, map cannot run into the second array from object.

[
    {
        "Id": "tryuk34io98i",
        "src": "planet",
        "gwt": {
            "gwtId": 918,
            "name": "Request"
        },
        "serve": "Transit1",
        "childNested": [
            {
                "name": "xxl",
                "version": "001",
                "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                "solved": {
                    "id": "tik",
                    "name": "face",
                    "isOn": "false"
                },
                "externalRef": [
                    {
                        "type": "eight",
                        "uri": "git"
                    },
                    {
                        "type": "two",
                        "uri": "git"
                    }
                ],
                "project": {
                    "name": "InProgress",
                    "version": "1",                    
                    "active": true
                },
                "used": 0,
                "internal": false
            }
        ],
        "affe": 0
    },
    {
        "Id": "987ytrdfghv",
        "src": "Space",
        "gwt": {
            "gwt": 918,
            "name": "Request"
        },
        "serve": "Transit",
        "childNested": [
            {
                "name": "xxs",
                "version": "02",
                "description": "Nullam sed lorem nec sem lobortis porta. Morbi vitae lorem velit.",
                "solved": {
                    "id": "tok",
                    "name": "back face",
                    "isOn": true
                },
                "externalRef": [
                    {
                        "type": "one",
                        "uri": "http"
                    },
                    {
                        "type": "two",
                        "uri": "http"
                    }
                ],
                "project": {
                    "name": "Fail",
                    "version": "1.1",
                    "active": false
                },
                "used": 0,
                "internal": false
            }
        ],
        "affe": 0
    }
]
3
  • Because .map() always returns an array: data.map((nested0) => nested0.childNested.map(...)) o.O Commented Apr 12, 2022 at 7:05
  • 1
    Have a look at .reduce() or .flatMap() or .flat() Commented Apr 12, 2022 at 7:07
  • @Andreas hmmm but that is weird because if I'm adding that in the jsx is rendering ok, but I need to expose the data . Commented Apr 12, 2022 at 7:07

3 Answers 3

4

Using the combination of flatMap, map and destructuring can simplify something like below. (PS. Just interpreted the data in your case, Update your data model if you still an issue)

const responses = [
  {
    data: {
      id: "123",
      capacity: 20,
      childNested: [{ date: { name: "foo1" } }, { date: { name: "foo2" } }],
    },
  },
  {
    data: {
      id: "456",
      capacity: 40,
      childNested: [{ date: { name: "bar" } }],
    },
  },
];

const output = responses.flatMap(({ data }) =>
  data.childNested.map(({ date: { name } }) => ({
    id: data.id,
    name: data.capacity,
    date: name,
  }))
);

console.log(output)

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

3 Comments

This is looking good but I'm not sure why is crashing on the map function, however my json data looks a bit different, I've just edit the post, can you please look a bit into the json structure.
It would be very helpful for members to answer if the question has what is the input currently, what is the expected output format/structure desired. Since the question has been updated with the actual input structure, would you also please update it with the expected / desired output structure. Also: in the input/json posted/updated in the question there is no prop capacity in the nested0 level. Where is this coming from?
@jsN00b got it, tnx
3

The solution may be one possible solution to achieve the below described output structure / format:

  id: nested0.id,         // outer-array "Id" prop
  name: nested0.serve,    // outer-array "serve" prop
  date: nested1.name      // inner-array "name" prop

Code Snippet

// method to obtain the array of transformed objects
const transformData = arr => (
  arr.flatMap(        // iterate the outer-array using "flatMap()"
    ({ Id, serve, childNested }) => (   // de-structure to directly access props
      childNested.map(          // iterate over inner-array "childNested"
        ({ name }) => ({        // de-structure to directly access "name" prop
          id: Id,               // structure the desired output object
          name: serve,
          date: name
        })
      )
    )
  )             // implicit "return" will send the result of "flatMap()"
);

const rawData = [{
    "Id": "tryuk34io98i",
    "src": "planet",
    "gwt": {
      "gwtId": 918,
      "name": "Request"
    },
    "serve": "Transit1",
    "childNested": [{
      "name": "xxl",
      "version": "001",
      "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
      "solved": {
        "id": "tik",
        "name": "face",
        "isOn": "false"
      },
      "externalRef": [{
          "type": "eight",
          "uri": "git"
        },
        {
          "type": "two",
          "uri": "git"
        }
      ],
      "project": {
        "name": "InProgress",
        "version": "1",
        "active": true
      },
      "used": 0,
      "internal": false
    }],
    "affe": 0
  },
  {
    "Id": "987ytrdfghv",
    "src": "Space",
    "gwt": {
      "gwt": 918,
      "name": "Request"
    },
    "serve": "Transit",
    "childNested": [{
      "name": "xxs",
      "version": "02",
      "description": "Nullam sed lorem nec sem lobortis porta. Morbi vitae lorem velit.",
      "solved": {
        "id": "tok",
        "name": "back face",
        "isOn": true
      },
      "externalRef": [{
          "type": "one",
          "uri": "http"
        },
        {
          "type": "two",
          "uri": "http"
        }
      ],
      "project": {
        "name": "Fail",
        "version": "1.1",
        "active": false
      },
      "used": 0,
      "internal": false
    }],
    "affe": 0
  }
];

console.log(transformData(rawData));

Explanation

Inline comments in the snippet are added.

Comments

0

Because you are using the nested Map Function, First Map returns a second map. Both Maps will return an array.

4 Comments

I get it but why on jsx is working ? data.map((nested0, index) => nested0.childNested((nested1) => ( <tbody key={index}> ......
Because react doesn't care how deeply you nest arrays.
@CherryDT mmm, oke, do you know any other methods how to iterate through a nest json and expose the data ?
As was already mentioned in the comments above, all you need to do is to flatten the array. You can either replace the outer map with flatMap or call .flat() on the result.

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.