Home > OS >  how to convert an array to a array of objects with additional information in react using map when do
how to convert an array to a array of objects with additional information in react using map when do

Time:06-08

I'm new with react and I'm stuck at a problem, kindly help me. array looks like this: surveyors=[jj,kk]

The length of array can be variable i.e.there can be more values. what i want to send in post api is:

data:[
   { 
    name:"kk",
    is_active:True,
    company:26
    },
    {
    name: "jj",
    is_active:True,
    company:26
    }
 ]

I'm using postapi like this:

  const postURL = moduleURL("url");
      requests({
        method: "post",
        url: postURL,
        data: [
          
          { 
    name:"kk",
    is_active:True,
    company:26
    },
    {
    name: "jj",
    is_active:True,
    company:26
    }
    
      ],
      })
        .then((response) => {
          console.log(response);
          
        })
        .catch((err) => console.log(err));
    }

if there was a fixed data i could do it but since the data in array surveyor is variable i cannot fix it. note- company here is the company id that i have stored in a variable and it will be same for every object in array and is_active will always be true.

CodePudding user response:

var supervisor=["jj","kk"];
var result = supervisor.map(s => {return {name: s, is_active:true, company:26} });
console.log(result)

CodePudding user response:

use map to create a new array of objects with extra attributes;

const supervisors = ["jj", "kk"];
const modifiedSupervisors = supervisors.map(item => ({name: item, is_active:true, company:26}));

now you can use this data in api call data: modifiedSupervisors,

  • Related