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

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

Comments

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 Comment

the 2nd one is cleaner, thanks! I think can use spread one liner as well.
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));

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.