0

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

0

2 Answers 2

4

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)

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

Comments

1

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)

1 Comment

Thanks, I cannot use startsWidth as im using an old js engine (spidermonkey 1.8)

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.