Method to search JSON for a partial value match and apply a property

2.9k views Asked by At

Hi I need to search a JSON response for all values of the key "columnName" that begin (only begin) with a specific string pattern of...

"IDM_"

For all matches I want to include a key/value "IDM":true and for any unmatched items "IDM":false on each object.

Thanks in advance.

{
"columnPermissions": [{
    "$id": "1474",
    "columnName": "IDM_ID"
}, {
    "$id": "1475",
    "columnName": "IDM_CreateDate"
}, {
    "$id": "1476",
    "columnName": "IDM_CreatedBy"
}, {
    "$id": "1480",
    "columnName": "First_Name"
}, {
    "$id": "1481",
    "columnName": "Last_Name"
}]

}
3

There are 3 answers

0
adiga On BEST ANSWER

You can loop through the columnPermissions array and set IDM property based on whether columnName startsWith "IDM_"

const input = {"columnPermissions":[{"$id":"1474","columnName":"IDM_ID"},{"$id":"1475","columnName":"IDM_CreateDate"},{"$id":"1476","columnName":"IDM_CreatedBy"},{"$id":"1480","columnName":"First_Name"},{"$id":"1481","columnName":"Last_Name"}]}

input.columnPermissions.forEach(a =>
  a.IDM = a.columnName.startsWith("IDM_")
)

console.log(input)

0
Kris D. J. On

I think you could do it like this:

let data = JSON.parse({
"columnPermissions": [{
  "$id": "1474",
  "columnName": "IDM_ID"
  }, {
  "$id": "1475",
  "columnName": "IDM_CreateDate"
  }, {
  "$id": "1476",
  "columnName": "IDM_CreatedBy"
  }, {
  "$id": "1480",
  "columnName": "First_Name"
  }, {
  "$id": "1481",
  "columnName": "Last_Name"
  }]
});

data = data.columnPermissions.map(column => Object.assign({}, { 'IDM': 
column.columnName.includes('IDM_') });
2
Ziv Ben-Or On
const newResponse = response.columnPermissions
    .map(c=> { ...c, 'IDM': c.columnName.includes('IDM_') });