Get an clean strings from array of objects

Viewed 33

I have an array of objects, and in this array of objects there is a string:

[
  {
    "id": 2240,
    "relatedId": "1000"
  },
  {
    "id": 1517,
    "relatedId": "100200"
  },
  {
    "id": 1517,
    "relatedId": "{{100200}}"
  },
  {
    "id": 2236,
    "relatedId": "{{271}}+{{269}}+{{267}}"
  }
]

I need to get back only the related ID keys that have "{{" or "}}" in them, then I need to strip out anything that's not a number and return an array of those numbers so the above would look like:

[100200,271,269,267]

Here is my attempt, which works:

const objArray = [
  {
    "id": 2240,
    "relatedId": "1000"
  },
  {
    "id": 1517,
    "relatedId": "100200"
  },
  {
    "id": 1517,
    "relatedId": "{{100200}}"
  },
  {
    "id": 2236,
    "relatedId": "{{271}}+{{269}}+{{267}}"
  }
];

const numArray = objArray.map(v => v.relatedId).filter(el => el.includes('{{'))
      .map(v => v.replace(/[{{}}]/g,'').split('+')).flat()
      .map(Number);
      
console.log(numArray)

However, is there a nicer way to do this? It feels like there should be a simpler way.

2 Answers

One option would be to join the strings into one, then use a global regular expression to match everything between brackets.

const objArray=[{id:2240,relatedId:"1000"},{id:1517,relatedId:"100200"},{id:1517,relatedId:"{{100200}}"},{id:2236,relatedId:"{{271}}+{{269}}+{{267}"}];

const numArray = objArray
    .map(v => v.relatedId)
    .join('')
    .match(/(?<={{)\d+/g)
    .map(Number);
      
console.log(numArray)

If there might not be any match anywhere, .match will return null - if that's a possibility, to avoid throwing an error, change to

const objArray=[{id:2240,relatedId:"1000"},{id:1517,relatedId:"100200"},{id:1517,relatedId:"{{100200}}"},{id:2236,relatedId:"{{271}}+{{269}}+{{267}"}];

const numArray = (
    objArray
        .map(v => v.relatedId)
        .join('')
        .match(/(?<={{)\d+/g)
    || []
)
    .map(Number);
      
console.log(numArray)

This is my take on it:

objArray.flatMap(o=>o.relatedId.match(/(?<={{)\d+(?=}})/g)||[]).map(Number)

** Note:
This uses lookbehind match (not supported by Safari and Firefox) and flatMap (introduced in ES2019)

Related