0

I have a structure like

  const test = [
    {
      items: [
        {
          id: "tete",
        },
        {
          id: "tete",
        },
      ],
    },
    {
      items: [
        {
          id: "tete",
        },
      ],
    },
  ];

How go i get all the 'id' value from these array using javascript.

1
  • You could use a combination of reduce and map, such as: const ids = test.reduce((a, b) => [...a, ...b.items.map(c => c.id)], []). you can look at the documentation for these functions on the MDN reduce and map Commented Nov 10, 2022 at 20:30

2 Answers 2

1

The new flatMap can do it all in one line with the regular map:

const test = [{items:[{id:"tete",},{id:"tete",},],},{items:[{id:"tete"}]}];

const result = test.flatMap((e) => e.items.map((i) => i.id));

console.log(result);

It is equivalent to the following:

const result = test.map((e) => e.items.map((i) => i.id)).flat();
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to remove duplicates, you could use Set after you got all the ids.
0

This is one option to extract the id values:

const test = [
    {
        items: [
            {
                id: "tete",
            },
            {
                id: "tete",
            },
        ],
    },
    {
        items: [
            {
                id: "tete",
            },
        ],
    },
];

const ids = test.reduce((acc, element) => {
    for (const item of element.items) {
        acc.push(item.id);
    }
    return acc;
}, []);

console.log(ids);

1 Comment

one-liner for the callback: acc.concat(element.items.map(({ id }) => id)))

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.