skip to Main Content

I have a response from an API call and I would like to change the name of the output. Here is the object:

{
  "sales": 312,
  "city": "Berlin",
}

My desired output is:

{
  "value": 312,
  "name": "Berlin",
}

I tried this code:

const dicts = data
const array = []
for (let dict in dicts) {
    const dictionary = dict
    Object.assign(dictionary, { name: dictionary.oldKey })['city']
    Object.assign(dictionary, { value: dictionary.oldKey })['sales']
    delete dictionary['city'];
    delete dictionary['sales'];
    array.push(dictionary);
}
return array

But I got an empty array as a result.

Could you please help me with this? I am new to Javascript and will use this code in Budibase to create an app.

2

Answers


  1. you can achieve this by creating a new object with the desired property

    // Original object from the API
    const original = {
      "sales": 312,
      "city": "Berlin"
    };
    
    // Create a new object with the desired property names
    const desired = {
    "value": original["sales"],
    "name": original["city"]
    };
    
    console.log(desired);
    Login or Signup to reply.
  2. Is there any reason you’re trying to mutate the objects in place? A more typical approach would be somehting like this.

    return data.map(item => {
      return {
        value: item.sales,
        name: item.city,
      }
    }
    

    See Array.prototype.map() for reference.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search