Marcos ..
Marcos ..

Reputation: 3

Remove object key prefixes nodejs

This is my first post. I don't like ask help in forums, but I have no choice. I spent a lot of days trying resolve this but I haven't found any solution.

All my problem start with an database query that returns this.

{
"prod_format": "400 ml",
"prod_brand": "Marca",
"prod_image": "192.168.1.45/mini/1046332bb531ab3.jpg",
"prod_name": "Gel de baño o ducha",
"prod_pvp": 2.20,
"prod_shops": [
  {
    "prod_price": 2.29,
    "prod_shop": {
      "prod_shopID": 2,
      "prod_shop_name": "Tienda",
      "prod_shop_image": "192.168.1.45/shops/d4d4sw2.jpg"
    }
  },
  {
    "prod_price": 2.19,
    "prod_shop": {
      "prod_shopID": 5,
      "prod_shop_name": "Tienda",
      "prod_shop_image": "192.168.1.45/shops/g4hbe72.jpg"
    }
  }
]
}

I want remove prefixes of keys, prod_ and shop_ in this case.

I can't do this by hand because this is only one of multiple queries that i use, and this data can change, i need an dynamic function that remove these prefixes, to use with more prefixes and more queries.

So far I have been trying:

In conclusion I want an function that if I put the upper object, I get this code.

{
"format": "400 ml",
"brand": "Marca",
"image": "http://192.168.1.45/mini/1046332bb531ab3.jpg",
"name": "Gel de baño o ducha",
"pvp": 2.20,
"shops": [
  {
    "price": 2.29,
    "shop": {
      "shopID": 2,
      "name": "Tienda",
      "image": "http://192.168.1.45/shops/d4d4sw2.jpg"
    }
  },
  {
    "price": 2.19,
    "shop": {
      "shopID": 5,
      "name": "Tienda",
      "image": "http://192.168.1.45/shops/g4hbe72.jpg"
    }
  }
]
}

PS: I can't edit the original object, because it comes of elasticsearch and i can't edit object keys.

Thanks in advance, I hope that anyone can help me.

Upvotes: 0

Views: 1847

Answers (1)

Rob
Rob

Reputation: 11788

Why don't you simply treat your Json data as a string and then replace '"_prod' with '"'? That would remove all occurances of this prefix.

myJsonString.replace('"_prod', '"');

Update: If your values may contain your prefixes, you better use regular expressions instead, just to make sure you only change the keys.

Upvotes: 3

Related Questions