-1

I have an array of objects and I need to rename the keys.

This is my approach:

Convert array of objects to JSON, replace the key and then do a JSON.parse

Replacing the oldKey with newKey is failing as this is a array!

Here is my JSON string.

str "[{\"194240_0900217\":\"500\"},{\"194242_0900294\":\"600\"}]"

I need like this:

str "[{\"194240\":\"500\"},{\"194242\":\"600\"}]"

Is there any other better approach to achieve this?

GG.
  • 21,083
  • 14
  • 84
  • 130
ryog
  • 122
  • 4

2 Answers2

1

This is the Regex

  var str="[{\"194240_0900217\":\"500\"},{\"194242_0900294\":\"600\"}]"
  var a=str.replace(/(_\d+)/g,"")
  console.log(a); 
// [{"194240":"500"},{"194242":"600"}]

a jsfiddle

Yehia Awad
  • 2,898
  • 1
  • 20
  • 31
0

Use a for in loop and use either delete after adding a replacement property or just set the old property to undefined depending on your preference after reading How do I remove a property from a JavaScript object?

var data = {
    "194240_0900217": "500",
    "194242_0900294": "600"
};

var k,
    matches;

console.log(data);

for (k in data) {
    if (data.hasOwnProperty(k)) {
        matches = k.match(/(\d+)_\d+/);
        if (matches) {
            data[matches[1]] = data[k];
            delete data[k];
        }
    }
}

console.log(data);

This prints:

{ '194240_0900217': '500', '194242_0900294': '600' }
{ '194240': '500', '194242': '600' }
Community
  • 1
  • 1
zero298
  • 25,467
  • 10
  • 75
  • 100