0

I am working on an angular project and I have an object like this

const obj = {
  fruits: ['apple', 'orange', 'None'],
  nation: ['usa'],
  city: ['New York', 'Delhi', 'None'],
  name: ['one', 'two'],
}

if the object key values have a 'None' value I have to remove the other values and keep it 'None' value only.

The answer looks like below:

const obj = {
  fruits: ['None'],
  nation: ['usa'],
  city: ['None'],
  name: ['one', 'two'],
}

Thanks in advance

1 Answer 1

1

Loop through object, if value includes None, replace the value to the key with ['None'].

Object.entries(obj).forEach(([k, v]) => {
  if (v.includes('None')) obj[k] = ['None']
})

const obj = {
  fruits: ['apple', 'orange', 'None'],
  nation: ['usa'],
  city: ['New York', 'Delhi', 'None'],
  name: ['one', 'two'],
}
  
Object.entries(obj).forEach(([k, v]) => {
  if (v.includes('None')) obj[k] = ['None']
})

console.log(obj)

For typescript playground.

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

4 Comments

angular6 typescript throwing error 'error TS2339: Property 'includes' does not exist on type '{}'
Does your obj value always has array type ?
Yes. I have to send the payload above format only. obj value always has array type
The error indicates the value could be {}. It works at this playground.

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.