Home > Enterprise >  Adding a prefix to the key of an object in axios
Adding a prefix to the key of an object in axios

Time:03-28

I have the object

data = {
    others: [
        {
            code: "A", label: "0-A"
        },
        {
            code: "B", label: "0-B"
        },
        ...,
        {
            code: "N", label: "0-N"
        }
    ]
}

And I need to add the other_ prefix to code value(example, other_N) before sending it to the axios query:

await axios.post(`${URL}`, { data })

CodePudding user response:

Something like this

let data = {
  others: [{
      code: "A",
      label: "0-A"
    },
    {
      code: "B",
      label: "0-B"
    },
    {
      code: "N",
      label: "0-N"
    }
  ]
};

let modifiedData = data.others.map(x => {
  x.code = `other_${x.code}`;
  return x;
})

console.log(modifiedData);

CodePudding user response:

you can use the Array.map function to manipulate the data object

data.others.map(x => { return { other_code: x.code, label: x.label }})
  • Related