0

I want to send a data attribute to an API server only if the method is add, if it's delete, I don't don't want to send my data.

I have

var body =
{
    id: 1,
    method: method,
    params: [
        {
            data: {
                "key1" : "value1",
                "key2" : "value2",
                "key3" : "value3"
            },

            url: `/url/anything`
        }
    ],
    session: session,
    verbose: 1
};

I tried

if(method == 'delete') {
    _.pick(body.params[0], ['data']);
}

I also tried

if(method == 'delete') {
    _.pick(body.params[0],'data');
}

For some reason, I still see that I still sending the data.

How would one go about debugging this?

halfer
  • 19,824
  • 17
  • 99
  • 186
code-8
  • 54,650
  • 106
  • 352
  • 604
  • Use `===` not `==` ... doesn't solve your issue, but it's best practice – Dexygen Jun 01 '18 at 16:20
  • 2
    Possible duplicate of [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – str Jun 01 '18 at 16:28

3 Answers3

1

if you take a look at lodash pick documentation you'll see that it doesn't change the source object instead its create a new object from the source object properties and returns the new object , if you want to remove the data property from the source object , you can use the unset method from lodash which removes a property from an object or a set of props , also you can use the delete operator

mostafa tourad
  • 4,308
  • 1
  • 12
  • 21
1

use _.assign:

var body =
{
    id: 1,
    method,
    params: [
        _.assign({url: `/url/anything`}, method === 'delete'
            ? null
            : {
                  data: {
                      "key1" : "value1",
                      "key2" : "value2",
                      "key3" : "value3"
                  }
              }
        ) 
    ],
    session,
    verbose: 1
};
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
0

You may need to do this.

if(method === 'delete') {
    body.params[0].data = undefined;
}

In this case, we delete all of the content of data by assign undefined.

  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Ethan Jun 01 '18 at 17:41