Home > Back-end >  adding more key value pair to an object javascript
adding more key value pair to an object javascript

Time:03-25

I have a method which accept 2 values

getCreateRequest = function (field, required) {
  return {
    additionalFields: [
      {
        field: field,
        required: required
      }
    ]
  };
};

I need to pass following values to this method

{ field: "PHONE", required: true },
{ field: "COUNTRY", required: true },
{ field: "MOBILE", required: true }

The method i wrote to do is following:

 let request = getCreateRequest ("PHONE", true);
 request.push("COMPANY", true);

but it failed to push more into the request and throw this error->request.push is not a function not sure how to do it in proper way

CodePudding user response:

If you want your request to be an array then do this:

getCreateRequest = function (field, required) {
  return [
    {
      field: field,
      required: required,
    },
  ];
};

let request = getCreateRequest("PHONE", true);
request.push({ field: "MOBILE", required: true });

console.log(request);

CodePudding user response:

getCreateRequest = function (field, required) {
  return {
    additionalFields: [
      {
        field: field,
        required: required
      }
    ]
  };
};

Your getCreteRequest function is returning Object. So if you want to fix it. You can:

request['additionalFields'].push({ field: "MOBILE", required: true });

CodePudding user response:

This appears like something that can be accomplished without using any user-defined functions as follows.

const data = { additionalFields:[] };

data.additionalFields.push(...[
    { field: "PHONE", required: true },
    { field: "COUNTRY", required: true },
    { field: "MOBILE", required: true }
]);

console.log( data );

A Class

However, if you needed to define your own methods, such as Fields#addFields() below, you can define a class. Instead of naming the method addFields I could have named it push but I chose not to. And, you can chain the calls - as long as this is returned.

class Fields {
    constructor(field, required) {
        this.data = {additionalFields: [{field, required}]};
        return this;
    }
    
    get fields() {
        return this.data;
    }
    
    addFields(field, required) {
        this.data.additionalFields.push({field, required});
        return this;
    }
}

const fields = new Fields("HOME", true);

console.log( fields.fields );

fields.addFields("MOBILE", false);

console.log( fields.fields );

fields.addFields("EMAIL", true)
      .addFields("BEEPER", false)
      .addFields("DAD", true);

console.log( fields.fields );

  • Related