1

I am having one form and will get values from the input. On button click, I am forming one object like below,

let data = filter : {
    metadata : {
        name: apple,
        type: fruits
    },
    match_attributes: {
        value : code_1
    }
}

Here, I need to remove the object "match_attributes", if "value" key is empty. My expected output will be like below,

let data = filter : {
    metadata : {
        name: apple,
        type: fruits
    }
}

I tried by something like this but not worked,

    let test = {};
            if(this.getValue) {
             test =   match_attributes : {
                    value : this.getValue
                }
            }


filter : {
match_metadata : {
    name: this.name,
    type: this.type
},
test
}

My Output :

let data = filter : {
        metadata : {
            name: this.fruitName,
            type: this.fruitType
        },
        { }
    }

Is there anyway to do this. Cheers.

4
  • Please click edit, then [<>] snippet editor and make a minimal reproducible example Commented Apr 2, 2020 at 9:42
  • What is this.getValue Commented Apr 2, 2020 at 9:44
  • you mean if your key doenst exist or if the value for the key value is empty? Commented Apr 2, 2020 at 9:45
  • To delete a specific key from an object use delete -> delete data.filter.match_attributes Commented Apr 2, 2020 at 9:46

3 Answers 3

1

The most straightforward way to conditionally add properties to an object is like this:

let data = {
    metadata : {
        name: apple,
        type: fruits
    }
}

if (code_1) {
   data.match_attributes = {
      value : code_1
   }
}

You can also delete already existing stuff from objects like this:

let data = {
    metadata : {
        name: apple,
        type: fruits
    },
   match_attributes: {
      value: code_1
   }
}

if (!data.match_attributes.value) {
   delete data.match_attributes
}

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

Comments

0

let data = 
{
'filter' : {
    'metadata' : {
        'name': 'apple',
        'type': 'fruits'
    },
    'match_attributes': {
        'value' : ''
    }
}
}
if(!data.filter.match_attributes.value){
delete data.filter.match_attributes
}

console.log(data);

Yes, you can use delete operator to do that. Hope this helps!

Comments

0

You could construct the base object first, then add the (match_attributes) object only when it is available:

let test = {
  match_metadata : {
    name: this.name,
    type: this.type
  }
}

if(this.getValue) {
  test.match_attributes = {
    value : this.getValue
  }
}

Comments

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.