Home > Software design >  How to get single key from array of array in javascript?
How to get single key from array of array in javascript?

Time:11-11

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related