Home > other >  Javascript:remove parameters/keys/properties from object matching string
Javascript:remove parameters/keys/properties from object matching string

Time:09-01

I have the following script which checks if my object has object properties starting with addr. how can I remove those properties from the object? as well as create a new object containing just those properties removed.

const dataObj = {
  firstName: "David Dynamic",
  id: "13249906",
  lastName: "Garcia",
  address1: "Test Address1",
  address2: "Test Address2"
}

if (Object.keys(dataObj).some(function(k) {
    return ~k.indexOf("addr")
  })) {
  console.log('Has address fields');
} else {
  console.log('Does not have address fields');
}

CodePudding user response:

Create the new object first, then copy the object properties, then use the delete keyword.

const dataObj = {
  firstName: "David Dynamic",
  id: "13249906",
  lastName: "Garcia",
  address1: "Test Address1",
  address2: "Test Address2"
}

const newObj = {}

for (const key in dataObj) {
    if (key.indexOf("addr") != -1) {
      newObj[key] = dataObj[key]
      delete dataObj[key]
    }
}

console.log(dataObj)
console.log(newObj)

CodePudding user response:

Interate over object entries, delete those starting with 'addr' and add them to accumulation object in reduce function:

const dataObj = {
    firstName: "David Dynamic",
    id: "13249906",
    lastName: "Garcia",
    address1: "Test Address1",
    address2: "Test Address2"
}

function extractAddrProperties(obj) {
    return Object.entries(obj).reduce((result, [key, value]) => {
        if (key.startsWith('addr')) {
            delete obj[key]
            result[key] = value
        }

        return result
    }, {})
}

console.log(extractAddrProperties(dataObj))
console.log(dataObj)

  • Related