imjayabal
imjayabal

Reputation: 819

How to remove other values in a object key array if particular value exist?

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

Upvotes: 0

Views: 33

Answers (1)

akuiper
akuiper

Reputation: 214917

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.

Upvotes: 1

Related Questions