Home > Blockchain >  flatten array of object with one loop
flatten array of object with one loop

Time:11-01

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related