1

I have this array of object, I want to extract its ids.

const arr = [
    
    {
        "id": "1",
    },
    {
        "id": "2",
        "options": [
            {
                "id": "2.1",
            }
        ]
    },
]

I did this

const one = arr.map(ob => ob.id)
const two = arr.flatMap(ob => ob.options).map(ob => ob?.id).filter(Boolean)

console.log([...one, ...two])

which worked fine, it prints ['1', '2', '2.1'] which is what I wanted but is there any simpler or shorter way to do it?

3 Answers 3

2

Recursive with foreach

const arr = [{
    "id": "1",
  },
  {
    "id": "2",
    "options": [{
      "id": "2.1",
    }]
  },
]

const getResult = (array, result = []) => {
  array.forEach(val => {
    result.push(val.id)

    if (val.options) {
      result = getResult(val.options, result)
    }
  })

  return result
}

console.log(getResult(arr))

1

Here's one possible approach - .concat onto an array of just the parent id property inside the mapper callback.

const arr = [
    
    {
        "id": "1",
    },
    {
        "id": "2",
        "options": [
            {
                "id": "2.1",
            }
        ]
    },
];
const result = arr.flatMap(obj => [obj.id].concat(obj.options?.map(o => o.id) ?? []));
console.log(result);

Another is

const arr = [
    
    {
        "id": "1",
    },
    {
        "id": "2",
        "options": [
            {
                "id": "2.1",
            }
        ]
    },
];
const toId = obj => obj.id;
const result = arr.map(toId).concat(arr.flatMap(o => o.options?.map(toId) ?? []));
console.log(result);

1
  • the 2nd one is cleaner, thanks! I think can use spread one liner as well.
    – Florence
    Commented Nov 1, 2022 at 6:01
0

This generic approach will extract all id fields, without you needing to specify the structure (such as the options key):

const arr = [{"id":"1"},{"id":"2","options":[{"id":"2.1"}]}];
const f=o=>typeof o==='object'?Object.keys(o).flatMap(k=>k==='id'?[o[k]]:f(o[k])):[];
console.log(f(arr));

Not the answer you're looking for? Browse other questions tagged or ask your own question.