Search code examples
javascriptnode.jsobjectaxiosprefix

Adding a prefix to the key of an object in axios


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 })

Solution

  • 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);